Example usage for org.apache.http.client.protocol HttpClientContext getCredentialsProvider

List of usage examples for org.apache.http.client.protocol HttpClientContext getCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext getCredentialsProvider.

Prototype

public CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:org.apache.http.impl.execchain.ProtocolExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpRequest original = request.getOriginal();
    URI uri = null;/*  w w w.j  a v  a 2s.co m*/
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    request.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(request, route);

    final HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final int port = route.getTargetHost().getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Using virtual host" + virtualHost);
        }
    }

    HttpHost target = null;
    if (virtualHost != null) {
        target = virtualHost;
    } else {
        if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
            target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        }
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            CredentialsProvider credsProvider = context.getCredentialsProvider();
            if (credsProvider == null) {
                credsProvider = new BasicCredentialsProvider();
                context.setCredentialsProvider(credsProvider);
            }
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    // Run request protocol interceptors
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);

    this.httpProcessor.process(request, context);

    final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
    try {
        // Run response protocol interceptors
        context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
        this.httpProcessor.process(response, context);
        return response;
    } catch (final RuntimeException ex) {
        response.close();
        throw ex;
    } catch (final IOException ex) {
        response.close();
        throw ex;
    } catch (final HttpException ex) {
        response.close();
        throw ex;
    }
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

private void prepareRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpRequestWrapper currentRequest = handler.getCurrentRequest();
    final HttpRoute route = handler.getRoute();

    final HttpRequest original = currentRequest.getOriginal();
    URI uri = null;//from   www  . j a  v  a  2s  .  com
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    currentRequest.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(currentRequest, route);

    HttpHost target = null;
    if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, currentRequest);
    localContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    this.httpProcessor.process(currentRequest, localContext);
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

private boolean handleConnectResponse(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final RequestConfig config = localContext.getRequestConfig();
    if (config.isAuthenticationEnabled()) {
        final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
        if (credsProvider != null) {
            final HttpRoute route = handler.getRoute();
            final HttpHost proxy = route.getProxyHost();
            final HttpResponse currentResponse = handler.getCurrentResponse();
            final AuthState proxyAuthState = localContext.getProxyAuthState();
            if (this.authenticator.isAuthenticationRequested(proxy, currentResponse, this.proxyAuthStrategy,
                    proxyAuthState, localContext)) {
                return this.authenticator.handleAuthChallenge(proxy, currentResponse, this.proxyAuthStrategy,
                        proxyAuthState, localContext);
            }//from   ww w  .java  2s . com
        }
    }
    return false;
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

private boolean needAuthentication(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
    if (credsProvider != null) {
        final HttpRoute route = handler.getRoute();
        final HttpResponse currentResponse = handler.getCurrentResponse();
        HttpHost target = localContext.getTargetHost();
        if (target == null) {
            target = route.getTargetHost();
        }// w w w. j  a  v a 2s .c  o  m
        if (target.getPort() < 0) {
            target = new HttpHost(target.getHostName(), route.getTargetHost().getPort(),
                    target.getSchemeName());
        }
        final AuthState targetAuthState = localContext.getTargetAuthState();
        final AuthState proxyAuthState = localContext.getProxyAuthState();

        final boolean targetAuthRequested = this.authenticator.isAuthenticationRequested(target,
                currentResponse, this.targetAuthStrategy, targetAuthState, localContext);

        HttpHost proxy = route.getProxyHost();
        // if proxy is not set use target host instead
        if (proxy == null) {
            proxy = route.getTargetHost();
        }
        final boolean proxyAuthRequested = this.authenticator.isAuthenticationRequested(proxy, currentResponse,
                this.proxyAuthStrategy, proxyAuthState, localContext);

        if (targetAuthRequested) {
            return this.authenticator.handleAuthChallenge(target, currentResponse, this.targetAuthStrategy,
                    targetAuthState, localContext);
        }
        if (proxyAuthRequested) {
            return this.authenticator.handleAuthChallenge(proxy, currentResponse, this.proxyAuthStrategy,
                    proxyAuthState, localContext);
        }
    }
    return false;
}

From source file:org.jboss.as.test.integration.security.common.Utils.java

/**
 * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
 * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new
 * request is created with the provided credentials (basic authentication).
 *
 * @param url URL to which the request should be made
 * @param user Username (may be null)/*  w w  w. j  ava  2s . co  m*/
 * @param pass Password (may be null)
 * @param expectedStatusCode expected status code returned from the requested server
 * @param checkFollowupAuthState whether to check auth state for followup request - if set to true, followup
 *                               request is sent to server and 200 OK is expected directly (no re-authentication
 *                               challenge - 401 Unauthorized - is expected)
 * @return HTTP response body
 * @throws IOException
 * @throws URISyntaxException
 */
public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode,
        boolean checkFollowupAuthState) throws IOException, URISyntaxException {
    LOGGER.trace("Requesting URL " + url);

    // use UTF-8 charset for credentials
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8))
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory(Consts.UTF_8)).build();
    try (final CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).build()) {
        final HttpGet httpGet = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        }
        HttpEntity entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);

        HttpClientContext hc = new HttpClientContext();
        hc.setCredentialsProvider(new BasicCredentialsProvider());
        hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials);
        //enable auth
        response = httpClient.execute(httpGet, hc);
        statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode,
                statusCode);

        if (checkFollowupAuthState) {
            // Let's disable authentication for this client as we already have all the context neccessary to be
            // authorized (we expect that gained 'nonce' value can be re-used in our case here).
            // By disabling authentication we simply get first server response and thus we can check whether we've
            // got 200 OK or different response code.
            RequestConfig reqConf = RequestConfig.custom().setAuthenticationEnabled(false).build();
            httpGet.setConfig(reqConf);
            response = httpClient.execute(httpGet, hc);
            statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code returned after the authentication.", HttpURLConnection.HTTP_OK,
                    statusCode);
        }

        return EntityUtils.toString(response.getEntity());
    }
}

From source file:org.opennms.core.web.HttpClientWrapper.java

protected void enablePreemptiveAuth(final HttpClientBuilder builder) {
    /**/*from  ww w .j  a v a  2 s .c o m*/
     * Add an HttpRequestInterceptor that will perform preemptive authentication
     * @see http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/authentication.html
     */
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (context instanceof HttpClientContext) {
                final HttpClientContext clientContext = (HttpClientContext) context;
                final AuthState authState = clientContext.getTargetAuthState();
                final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
                final HttpHost targetHost = clientContext.getTargetHost();
                // If not authentication scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    final Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.update(new BasicScheme(), creds);
                    }
                }
            } else {
                throw new IllegalArgumentException("Not sure how to handle a non-HttpClientContext context.");
            }
        }

    };
    builder.addInterceptorFirst(preemptiveAuth);
}