Search in sources :

Example 1 with Authorization

use of org.apache.jmeter.protocol.http.control.Authorization in project jmeter by apache.

the class ProxyControl method createAuthorization.

/**
     * Detect Header manager in subConfigs,
     * Find(if any) Authorization header
     * Construct Authentication object
     * Removes Authorization if present 
     *
     * @param subConfigs {@link TestElement}[]
     * @param sampler {@link HTTPSamplerBase}
     * @return {@link Authorization}
     */
private Authorization createAuthorization(final TestElement[] testElements, HTTPSamplerBase sampler) {
    Header authHeader;
    Authorization authorization = null;
    // Iterate over subconfig elements searching for HeaderManager
    for (TestElement te : testElements) {
        if (te instanceof HeaderManager) {
            // headers should only contain the correct classes
            @SuppressWarnings("unchecked") List<TestElementProperty> headers = (ArrayList<TestElementProperty>) ((HeaderManager) te).getHeaders().getObjectValue();
            for (Iterator<?> iterator = headers.iterator(); iterator.hasNext(); ) {
                TestElementProperty tep = (TestElementProperty) iterator.next();
                if (tep.getName().equals(HTTPConstants.HEADER_AUTHORIZATION)) {
                    //Construct Authorization object from HEADER_AUTHORIZATION
                    authHeader = (Header) tep.getObjectValue();
                    //$NON-NLS-1$
                    String[] authHeaderContent = authHeader.getValue().split(" ");
                    String authType;
                    String authCredentialsBase64;
                    if (authHeaderContent.length >= 2) {
                        authType = authHeaderContent[0];
                        authCredentialsBase64 = authHeaderContent[1];
                        authorization = new Authorization();
                        try {
                            authorization.setURL(sampler.getUrl().toExternalForm());
                        } catch (MalformedURLException e) {
                            log.error("Error filling url on authorization, message:" + e.getMessage(), e);
                            //$NON-NLS-1$
                            authorization.setURL("${AUTH_BASE_URL}");
                        }
                        // if HEADER_AUTHORIZATION contains "Basic"
                        // then set Mechanism.BASIC_DIGEST, otherwise Mechanism.KERBEROS
                        authorization.setMechanism(authType.equals(BASIC_AUTH) || authType.equals(DIGEST_AUTH) ? AuthManager.Mechanism.BASIC_DIGEST : AuthManager.Mechanism.KERBEROS);
                        if (BASIC_AUTH.equals(authType)) {
                            String authCred = new String(Base64.decodeBase64(authCredentialsBase64));
                            //$NON-NLS-1$
                            String[] loginPassword = authCred.split(":");
                            authorization.setUser(loginPassword[0]);
                            authorization.setPass(loginPassword[1]);
                        } else {
                            // Digest or Kerberos
                            //$NON-NLS-1$
                            authorization.setUser("${AUTH_LOGIN}");
                            //$NON-NLS-1$
                            authorization.setPass("${AUTH_PASSWORD}");
                        }
                    }
                    // remove HEADER_AUTHORIZATION from HeaderManager 
                    // because it's useless after creating Authorization object
                    iterator.remove();
                }
            }
        }
    }
    return authorization;
}
Also used : Authorization(org.apache.jmeter.protocol.http.control.Authorization) MalformedURLException(java.net.MalformedURLException) Header(org.apache.jmeter.protocol.http.control.Header) TestElementProperty(org.apache.jmeter.testelement.property.TestElementProperty) ArrayList(java.util.ArrayList) TestElement(org.apache.jmeter.testelement.TestElement) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager)

Example 2 with Authorization

use of org.apache.jmeter.protocol.http.control.Authorization in project jmeter by apache.

the class ProxyControl method deliverSampler.

/**
 * Receives the recorded sampler from the proxy server for placing in the
 * test tree; this is skipped if the sampler is null (e.g. for recording SSL errors)
 * Always sends the result to any registered sample listeners.
 *
 * @param sampler      the sampler, may be null
 * @param testElements the test elements to be added (e.g. header manager) under the Sampler
 * @param result       the sample result, not null
 *                     TODO param serverResponse to be added to allow saving of the
 *                     server's response while recording.
 */
public synchronized void deliverSampler(final HTTPSamplerBase sampler, final TestElement[] testElements, final SampleResult result) {
    boolean notifySampleListeners = true;
    if (sampler != null) {
        if (USE_REDIRECT_DISABLING && (samplerRedirectAutomatically || samplerFollowRedirects) && result instanceof HTTPSampleResult) {
            final HTTPSampleResult httpSampleResult = (HTTPSampleResult) result;
            final String urlAsString = httpSampleResult.getUrlAsString();
            if (urlAsString.equals(LAST_REDIRECT)) {
                // the url matches the last redirect
                sampler.setEnabled(false);
                sampler.setComment("Detected a redirect from the previous sample");
            } else {
                // this is not the result of a redirect
                // so break the chain
                LAST_REDIRECT = null;
            }
            if (httpSampleResult.isRedirect()) {
                // Save Location so resulting sample can be disabled
                if (LAST_REDIRECT == null) {
                    sampler.setComment("Detected the start of a redirect chain");
                }
                LAST_REDIRECT = httpSampleResult.getRedirectLocation();
            } else {
                LAST_REDIRECT = null;
            }
        }
        if (filterContentType(result) && filterUrl(sampler)) {
            JMeterTreeNode myTarget = findTargetControllerNode();
            // OK, because find only returns correct element types
            @SuppressWarnings("unchecked") Collection<ConfigTestElement> defaultConfigurations = (Collection<ConfigTestElement>) findApplicableElements(myTarget, ConfigTestElement.class, false);
            // OK, because find only returns correct element types
            @SuppressWarnings("unchecked") Collection<Arguments> userDefinedVariables = (Collection<Arguments>) findApplicableElements(myTarget, Arguments.class, true);
            removeValuesFromSampler(sampler, defaultConfigurations);
            replaceValues(sampler, testElements, userDefinedVariables);
            sampler.setAutoRedirects(samplerRedirectAutomatically);
            sampler.setFollowRedirects(samplerFollowRedirects);
            sampler.setUseKeepAlive(useKeepAlive);
            sampler.setImageParser(samplerDownloadImages);
            Authorization authorization = createAuthorization(testElements, result);
            if (authorization != null) {
                setAuthorization(authorization, myTarget);
            }
            sampleQueue.add(new SamplerInfo(sampler, testElements, myTarget, getPrefixHTTPSampleName(), groupingMode));
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sample excluded based on url or content-type: {} - {}", result.getUrlAsString(), result.getContentType());
            }
            notifySampleListeners = notifyChildSamplerListenersOfFilteredSamples;
            result.setSampleLabel("[" + result.getSampleLabel() + "]");
        }
    }
    if (notifySampleListeners) {
        // SampleEvent is not passed JMeterVariables, because they don't make sense for Proxy Recording
        notifySampleListeners(new SampleEvent(result, "WorkBench"));
    } else {
        log.debug("Sample not delivered to Child Sampler Listener based on url or content-type: {} - {}", result.getUrlAsString(), result.getContentType());
    }
}
Also used : Arguments(org.apache.jmeter.config.Arguments) SampleEvent(org.apache.jmeter.samplers.SampleEvent) Authorization(org.apache.jmeter.protocol.http.control.Authorization) HTTPSampleResult(org.apache.jmeter.protocol.http.sampler.HTTPSampleResult) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) Collection(java.util.Collection) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement)

Example 3 with Authorization

use of org.apache.jmeter.protocol.http.control.Authorization in project jmeter by apache.

the class ParseCurlCommandActionTest method testCanAddAuthManagerInHttpRequest.

@Test
public void testCanAddAuthManagerInHttpRequest() throws Exception {
    ParseCurlCommandAction p = new ParseCurlCommandAction();
    AuthManager authManager = new AuthManager();
    Authorization authorization = new Authorization();
    authorization.setPass("passwd");
    authorization.setUser("user");
    authorization.setURL("http://jmeter.apache.org/");
    authorization.setMechanism(Mechanism.BASIC);
    authManager.addAuth(authorization);
    BasicCurlParser basicCurlParser = new BasicCurlParser();
    Request request = basicCurlParser.parse("curl 'http://jmeter.apache.org/' -u 'user:passwd'");
    Method method = getMethodFor("canAddAuthManagerInHttpRequest", Request.class, AuthManager.class);
    assertFalse((boolean) method.invoke(p, request, authManager), "When AuthManager contains this authorization, shouldn't add a AuthManager in Http Request");
    request = basicCurlParser.parse("curl 'http://jmeter.apache.org/' -u 'user1:passwd1'");
    assertTrue((boolean) method.invoke(p, request, authManager), "When AuthManager contains this url, but the username or password isn't the same," + "should add a AuthManager in Http Request");
}
Also used : Authorization(org.apache.jmeter.protocol.http.control.Authorization) BasicCurlParser(org.apache.jmeter.protocol.http.curl.BasicCurlParser) AuthManager(org.apache.jmeter.protocol.http.control.AuthManager) Request(org.apache.jmeter.protocol.http.curl.BasicCurlParser.Request) ParseCurlCommandAction(org.apache.jmeter.protocol.http.gui.action.ParseCurlCommandAction) Method(java.lang.reflect.Method) Test(org.junit.jupiter.api.Test)

Example 4 with Authorization

use of org.apache.jmeter.protocol.http.control.Authorization in project jmeter by apache.

the class ProxyControl method createAuthorization.

/**
 * Detect Header manager in subConfigs,
 * Find(if any) Authorization header
 * Construct Authentication object
 * Removes Authorization if present
 *
 * @param testElements {@link TestElement}[]
 * @param result       {@link HTTPSampleResult}
 * @return {@link Authorization}
 */
private Authorization createAuthorization(final TestElement[] testElements, SampleResult result) {
    Header authHeader;
    Authorization authorization = null;
    // Iterate over subconfig elements searching for HeaderManager
    for (TestElement te : testElements) {
        if (te instanceof HeaderManager) {
            // headers should only contain the correct classes
            @SuppressWarnings("unchecked") List<TestElementProperty> headers = (ArrayList<TestElementProperty>) ((HeaderManager) te).getHeaders().getObjectValue();
            for (Iterator<?> iterator = headers.iterator(); iterator.hasNext(); ) {
                TestElementProperty tep = (TestElementProperty) iterator.next();
                if (tep.getName().equals(HTTPConstants.HEADER_AUTHORIZATION)) {
                    // Construct Authorization object from HEADER_AUTHORIZATION
                    authHeader = (Header) tep.getObjectValue();
                    String headerValue = authHeader.getValue().trim();
                    // $NON-NLS-1$
                    String[] authHeaderContent = headerValue.split(" ");
                    String authType;
                    String authCredentialsBase64;
                    if (authHeaderContent.length >= 2) {
                        authType = authHeaderContent[0];
                        // if HEADER_AUTHORIZATION contains "Basic"
                        // then set Mechanism.BASIC_DIGEST, otherwise Mechanism.KERBEROS
                        Mechanism mechanism;
                        switch(authType) {
                            case BEARER_AUTH:
                                // This one will need to be correlated manually by user
                                return null;
                            case DIGEST_AUTH:
                                mechanism = Mechanism.DIGEST;
                                break;
                            case BASIC_AUTH:
                                mechanism = Mechanism.BASIC;
                                break;
                            default:
                                mechanism = Mechanism.KERBEROS;
                                break;
                        }
                        authCredentialsBase64 = authHeaderContent[1];
                        authorization = new Authorization();
                        authorization.setURL(computeAuthUrl(result.getUrlAsString()));
                        authorization.setMechanism(mechanism);
                        if (BASIC_AUTH.equals(authType)) {
                            String authCred = new String(Base64.decodeBase64(authCredentialsBase64), StandardCharsets.UTF_8);
                            // $NON-NLS-1$
                            String[] loginPassword = authCred.split(":");
                            if (loginPassword.length == 2) {
                                authorization.setUser(loginPassword[0]);
                                authorization.setPass(loginPassword[1]);
                            } else {
                                log.error("Error parsing BASIC Auth authorization header:'{}', decoded value:'{}'", authCredentialsBase64, authCred);
                                // we keep initial header
                                return null;
                            }
                        } else {
                            // Digest or Kerberos
                            // $NON-NLS-1$
                            authorization.setUser("${AUTH_LOGIN}");
                            // $NON-NLS-1$
                            authorization.setPass("${AUTH_PASSWORD}");
                        }
                    }
                    // remove HEADER_AUTHORIZATION from HeaderManager
                    // because it's useless after creating Authorization object
                    iterator.remove();
                    break;
                }
            }
        }
    }
    return authorization;
}
Also used : Authorization(org.apache.jmeter.protocol.http.control.Authorization) Header(org.apache.jmeter.protocol.http.control.Header) TestElementProperty(org.apache.jmeter.testelement.property.TestElementProperty) ArrayList(java.util.ArrayList) TestElement(org.apache.jmeter.testelement.TestElement) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement) NonTestElement(org.apache.jmeter.testelement.NonTestElement) Mechanism(org.apache.jmeter.protocol.http.control.AuthManager.Mechanism) HeaderManager(org.apache.jmeter.protocol.http.control.HeaderManager)

Example 5 with Authorization

use of org.apache.jmeter.protocol.http.control.Authorization in project jmeter by apache.

the class HTTPHC4Impl method executeRequest.

/**
     * Execute request either as is or under PrivilegedAction 
     * if a Subject is available for url
     * @param httpClient the {@link CloseableHttpClient} to be used to execute the httpRequest
     * @param httpRequest the {@link HttpRequest} to be executed
     * @param localContext th {@link HttpContext} to be used for execution
     * @param url the target url (will be used to look up a possible subject for the execution)
     * @return the result of the execution of the httpRequest
     * @throws IOException
     * @throws ClientProtocolException
     */
private CloseableHttpResponse executeRequest(final CloseableHttpClient httpClient, final HttpRequestBase httpRequest, final HttpContext localContext, final URL url) throws IOException, ClientProtocolException {
    AuthManager authManager = getAuthManager();
    if (authManager != null) {
        Subject subject = authManager.getSubjectForUrl(url);
        if (subject != null) {
            try {
                return Subject.doAs(subject, (PrivilegedExceptionAction<CloseableHttpResponse>) () -> httpClient.execute(httpRequest, localContext));
            } catch (PrivilegedActionException e) {
                log.error("Can't execute httpRequest with subject: {}", subject, e);
                throw new RuntimeException("Can't execute httpRequest with subject:" + subject, e);
            }
        }
        if (BASIC_AUTH_PREEMPTIVE) {
            Authorization authorization = authManager.getAuthForURL(url);
            if (authorization != null && Mechanism.BASIC_DIGEST.equals(authorization.getMechanism())) {
                HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                // Generate BASIC scheme object and 
                // add it to the local auth cache
                BasicScheme basicAuth = new BasicScheme();
                authCache.put(target, basicAuth);
                // Add AuthCache to the execution context
                localContext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
            }
        }
    }
    return httpClient.execute(httpRequest, localContext);
}
Also used : Authorization(org.apache.jmeter.protocol.http.control.Authorization) BasicScheme(org.apache.http.impl.auth.BasicScheme) AuthManager(org.apache.jmeter.protocol.http.control.AuthManager) PrivilegedActionException(java.security.PrivilegedActionException) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Subject(javax.security.auth.Subject)

Aggregations

Authorization (org.apache.jmeter.protocol.http.control.Authorization)8 ConfigTestElement (org.apache.jmeter.config.ConfigTestElement)3 AuthManager (org.apache.jmeter.protocol.http.control.AuthManager)3 Method (java.lang.reflect.Method)2 ArrayList (java.util.ArrayList)2 Header (org.apache.jmeter.protocol.http.control.Header)2 HeaderManager (org.apache.jmeter.protocol.http.control.HeaderManager)2 BasicCurlParser (org.apache.jmeter.protocol.http.curl.BasicCurlParser)2 Request (org.apache.jmeter.protocol.http.curl.BasicCurlParser.Request)2 ParseCurlCommandAction (org.apache.jmeter.protocol.http.gui.action.ParseCurlCommandAction)2 TestElement (org.apache.jmeter.testelement.TestElement)2 TestElementProperty (org.apache.jmeter.testelement.property.TestElementProperty)2 Test (org.junit.jupiter.api.Test)2 MalformedURLException (java.net.MalformedURLException)1 PrivilegedActionException (java.security.PrivilegedActionException)1 Collection (java.util.Collection)1 Subject (javax.security.auth.Subject)1 HttpHost (org.apache.http.HttpHost)1 AuthCache (org.apache.http.client.AuthCache)1 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)1