Example usage for org.apache.http.impl.auth BasicScheme BasicScheme

List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicScheme BasicScheme.

Prototype

@Deprecated
public BasicScheme(final ChallengeState challengeState) 

Source Link

Document

Creates an instance of BasicScheme with the given challenge state.

Usage

From source file:org.artifactory.util.ProxyPreemptiveAuthInterceptor.java

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    AuthState proxyAuthState = clientContext.getProxyAuthState();

    // If there's no auth scheme available yet, try to initialize it preemptively
    if (proxyAuthState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
        RouteInfo route = clientContext.getHttpRoute();
        if (route == null) {
            log.debug("No route found for {}", clientContext.getTargetHost());
            return;
        }/*from ww w.  j a va  2  s .  co  m*/

        HttpHost proxyHost = route.getProxyHost();
        if (proxyHost == null) {
            log.warn("No proxy host found in route {} for host {}", route, clientContext.getTargetHost());
            return;
        }

        Credentials creds = credsProvider
                .getCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()));
        if (creds == null) {
            log.info("No credentials found for proxy: " + proxyHost);
            return;
        }
        proxyAuthState.update(new BasicScheme(ChallengeState.PROXY), creds);
    }
}

From source file:org.apache.jena.atlas.web.auth.PreemptiveBasicAuthenticator.java

@Override
public void apply(AbstractHttpClient client, HttpContext httpContext, URI target) {
    this.authenticator.apply(client, httpContext, target);

    // Enable preemptive basic authentication
    // For nice layering we need to respect existing auth cache if present
    AuthCache authCache = (AuthCache) httpContext.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null)
        authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(this.isProxy ? ChallengeState.PROXY : ChallengeState.TARGET);
    // TODO It is possible that this overwrites existing cached credentials
    // so potentially not ideal.
    authCache.put(new HttpHost(target.getHost(), target.getPort()), basicAuth);
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:ua.pp.msk.cliqr.PostProcessorImpl.java

private void init(URL url, String user, String password) throws ClientSslException {
    this.targetUrl = url;
    HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());

    BasicAuthCache aCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(ChallengeState.TARGET);
    aCache.put(htHost, basicAuth);/*from  w w w.ja  v a  2s . com*/

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
    BasicCredentialsProvider cProvider = new BasicCredentialsProvider();
    cProvider.setCredentials(new AuthScope(htHost), creds);
    logger.debug("Credential provider: " + cProvider.toString());

    context = new BasicHttpContext();
    ClientContextConfigurer cliCon = new ClientContextConfigurer(context);
    context.setAttribute(ClientContext.AUTH_CACHE, aCache);
    //context.setAuthCache(aCache);
    cliCon.setCredentialsProvider(cProvider);
    //context.setCredentialsProvider(cProvider);
    SSLSocketFactory sslSocketFactory = null;
    try {
        //SSLContext trustySslContext = SSLContextBuilder.create().loadTrustMaterial( new TrustSelfSignedStrategy()).build();
        //sslConnectionSocketFactory = new SSLConnectionSocketFactory(trustySslContext, new CliQrHostnameVerifier());
        sslSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new CliQrHostnameVerifier());
    } catch (KeyManagementException ex) {
        logger.error("Cannot manage secure keys", ex);
        throw new ClientSslException("Cannot manage secure keys", ex);
    } catch (KeyStoreException ex) {
        logger.error("Cannot build SSL context due to KeyStore error", ex);
        throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex);
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Unsupported security algorithm", ex);
        throw new ClientSslException("Unsupported security algorithm", ex);
    } catch (UnrecoverableKeyException ex) {
        logger.error("Unrecoverable key", ex);
        throw new ClientSslException("Unrecoverrable key", ex);
    }

    DefaultHttpClient defClient = new DefaultHttpClient();
    defClient.setRedirectStrategy(new CliQrRedirectStrategy());
    defClient.setCredentialsProvider(cProvider);
    Scheme https = new Scheme("https", 443, sslSocketFactory);
    defClient.getConnectionManager().getSchemeRegistry().register(https);
    defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy());
    client = defClient;
}

From source file:de.adorsys.oauth.loginmodule.HTTPAuthenticationLoginModule.java

private boolean authenticate(String username, String password) throws LoginException {
    HttpHost targetHost = new HttpHost(restEndpoint.getHost(), restEndpoint.getPort(),
            restEndpoint.getScheme());//from  w ww  .  j a va2  s.co  m
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme(Consts.UTF_8);
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    HttpGet httpGet = new HttpGet(restEndpoint);

    CloseableHttpResponse userInfoResponse = null;
    try {
        userInfoResponse = HTTP_CLIENT.execute(httpGet, context);
        if (userInfoResponse.getStatusLine().getStatusCode() != 200) {
            LOG.error("Authentication failed for user {}, restEndpoint {} HTTP Status {}", username,
                    restEndpoint.toASCIIString(), userInfoResponse.getStatusLine());
            throw new LoginException("Authentication failed for user " + username + ", restEndpoint "
                    + restEndpoint.toASCIIString() + " HTTP Status " + userInfoResponse.getStatusLine());
        }
        String userInfoJson = readUserInfo(userInfoResponse);
        JSONObject userInfo = new JSONObject(userInfoJson);
        String principalId = userInfo.getString("principal");
        if (principalId == null) {
            LOG.error("could not read  field 'principal' for user {}. Response: {}", username, userInfoJson);
            throw new LoginException(
                    "could not read  field 'principal' for user " + username + ". Response: " + userInfoJson);
        }
        JSONArray roles = userInfo.getJSONArray("roles");

        populateSubject(principalId, roles);

        // we put them to shared stated that other login providers can also
        // authenticate
        sharedState.put("javax.security.auth.login.name", principalId);
        sharedState.put("javax.security.auth.login.password", password);
    } catch (IOException e) {
        throw new IllegalStateException("problem on http backend authentication", e);
    } finally {
        if (userInfoResponse != null) {
            try {
                userInfoResponse.close();
            } catch (IOException e) {
                ; // NOOP
            }
        }
    }
    return true;
}

From source file:org.switchyard.component.http.OutboundHandler.java

/**
 * Start lifecycle./*from  w w w. ja va2s .  c  om*/
 *
 * @throws HttpConsumeException If unable to load or access a HTTP uri
 */
@Override
protected void doStart() throws HttpConsumeException {
    String address = _config.getAddress();
    if (address != null) {
        _baseAddress = address;
    }
    String method = _config.getMethod();
    if (method != null) {
        _httpMethod = method;
    }
    String contentType = _config.getContentType();
    if (contentType != null) {
        _contentType = contentType;
    }
    // Create and configure the HTTP message composer
    _messageComposer = HttpComposition.getMessageComposer(_config);

    if (_config.hasAuthentication()) {
        // Set authentication
        if (_config.isBasicAuth()) {
            _authScope = createAuthScope(_config.getBasicAuthConfig().getHost(),
                    _config.getBasicAuthConfig().getPort(), _config.getBasicAuthConfig().getRealm());
            _credentials = new UsernamePasswordCredentials(_config.getBasicAuthConfig().getUser(),
                    _config.getBasicAuthConfig().getPassword());
            // Create AuthCache instance
            _authCache = new BasicAuthCache();
            _authCache.put(new HttpHost(_authScope.getHost(), _authScope.getPort()),
                    new BasicScheme(ChallengeState.TARGET));
        } else {
            _authScope = createAuthScope(_config.getNtlmAuthConfig().getHost(),
                    _config.getNtlmAuthConfig().getPort(), _config.getNtlmAuthConfig().getRealm());
            _credentials = new NTCredentials(_config.getNtlmAuthConfig().getUser(),
                    _config.getNtlmAuthConfig().getPassword(), "", _config.getNtlmAuthConfig().getDomain());
        }
    }
    if (_config.getProxyConfig() != null) {
        if (_config.getProxyConfig().getPort() != null) {
            _proxyHost = new HttpHost(_config.getProxyConfig().getHost(),
                    Integer.valueOf(_config.getProxyConfig().getPort()).intValue());
        } else {
            _proxyHost = new HttpHost(_config.getProxyConfig().getHost(), -1);
        }
        if (_config.getProxyConfig().getUser() != null) {
            _authScope = createAuthScope(_config.getProxyConfig().getHost(), _config.getProxyConfig().getPort(),
                    null);
            _credentials = new UsernamePasswordCredentials(_config.getProxyConfig().getUser(),
                    _config.getProxyConfig().getPassword());
            if (_authCache == null) {
                _authCache = new BasicAuthCache();
            }
            _authCache.put(_proxyHost, new BasicScheme(ChallengeState.PROXY));
        }
    }
    _timeout = _config.getTimeout();
}

From source file:org.dcache.webdav.transfer.CredentialServiceClient.java

private HttpPost buildRequest(String token, String host, String clientId, String clientSecret)
        throws UnsupportedEncodingException, AuthenticationException {
    UsernamePasswordCredentials clientCreds = new UsernamePasswordCredentials(clientId, clientSecret);
    BasicScheme scheme = new BasicScheme(Charsets.UTF_8);

    HttpPost post = new HttpPost(tokenEndPoint(host));
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
    params.add(new BasicNameValuePair("audience", clientId));
    params.add(new BasicNameValuePair("subject_token", token));
    params.add(new BasicNameValuePair("subject_token_type", TOKEN_TYPE));
    params.add(new BasicNameValuePair("scope", SCOPE));

    post.setEntity(new UrlEncodedFormEntity(params));
    post.addHeader(scheme.authenticate(clientCreds, post, new BasicHttpContext()));
    return post;// w ww .j  av  a 2s . c o  m
}

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

/**
 * Create a RESTEasy invoker client.//from   w w w .  j a  v  a 2 s . co  m
 *
 * @param basePath The base path for the class
 * @param resourceClass The JAX-RS Resource Class
 * @param method The JAX-RS Resource Class's method
 * @param model Configuration model
 */
public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) {
    Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
    _baseUri = createUri(basePath);
    if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class)
            && method.getReturnType().isInterface()) {
        _subResourcePath = createSubResourcePath(basePath, method);
    } else if (httpMethods == null || httpMethods.size() != 1) {
        throw RestEasyMessages.MESSAGES
                .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString());
    }
    _httpMethod = httpMethods.iterator().next();
    _resourceClass = resourceClass;
    _method = method;
    try {
        _uri = (UriBuilder) URIBUILDER_CLASS.newInstance();
    } catch (InstantiationException ie) {
        throw new RuntimeException(ie);
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    }
    _uri.uri(_baseUri);
    if (_resourceClass.isAnnotationPresent(Path.class)) {
        _uri.path(_resourceClass);
    }
    if (_method.isAnnotationPresent(Path.class)) {
        _uri.path(_method);
    }

    _providerFactory = new ResteasyProviderFactory();

    boolean useBuiltins = true; // use builtin @Provider classes by default
    if (model.getContextParamsConfig() != null) {
        Map<String, String> contextParams = model.getContextParamsConfig().toMap();

        // Set use builtin @Provider classes
        String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS);
        if (registerBuiltins != null) {
            useBuiltins = Boolean.parseBoolean(registerBuiltins);
        }

        // Register @Provider classes
        List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams);
        if (providerClasses != null) {
            for (Class<?> pc : providerClasses) {
                _providerFactory.registerProvider(pc);
            }
        }

        List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams);
        if (interceptors != null) {
            for (ClientErrorInterceptor interceptor : interceptors) {
                _providerFactory.addClientErrorInterceptor(interceptor);
            }
        }
    }
    if (useBuiltins) {
        _providerFactory.setRegisterBuiltins(true);
        RegisterBuiltin.register(_providerFactory);
    }

    _extractorFactory = new DefaultEntityExtractorFactory();
    _extractor = _extractorFactory.createExtractor(_method);
    _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null);
    _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null);
    ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method);

    // Client executor
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    int port = _baseUri.getPort();
    if (_baseUri.getScheme().startsWith("https")) {
        if (port == -1) {
            port = 443;
        }
        SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig());
        if (sslFactory == null) {
            sslFactory = SSLSocketFactory.getSocketFactory();
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory));
    } else {
        if (port == -1) {
            port = 80;
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory()));
    }
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpClient httpClient = new DefaultHttpClient(cm);
    _executor = new ApacheHttpClient4Executor(httpClient);
    // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory
    Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class,
            ClientExceptionMapper.class)[0];
    _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);

    // Authentication settings
    if (model.hasAuthentication()) {
        // Set authentication
        AuthScope authScope = null;
        Credentials credentials = null;
        if (model.isBasicAuth()) {
            authScope = createAuthScope(model.getBasicAuthConfig().getHost(),
                    model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm());
            credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(),
                    model.getBasicAuthConfig().getPassword());
            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()),
                    new BasicScheme(ChallengeState.TARGET));
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
        } else {
            authScope = createAuthScope(model.getNtlmAuthConfig().getHost(),
                    model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm());
            credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(),
                    model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain());
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);
    } else {
        ProxyModel proxy = model.getProxyConfig();
        if (proxy != null) {
            HttpHost proxyHost = null;
            if (proxy.getPort() != null) {
                proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue());
            } else {
                proxyHost = new HttpHost(proxy.getHost(), -1);
            }
            if (proxy.getUser() != null) {
                AuthScope authScope = new AuthScope(proxy.getHost(),
                        Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword());
                AuthCache authCache = new BasicAuthCache();
                authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY));
                ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope,
                        credentials);
                BasicHttpContext context = new BasicHttpContext();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
                ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
            }
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
    }
    Integer timeout = model.getTimeout();
    if (timeout != null) {
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
        HttpConnectionParams.setSoTimeout(httpParams, timeout);
    }
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

protected String execute(HttpRequestBase httpRequestBase)
        throws JSONWebServiceInvocationException, JSONWebServiceTransportException {

    signRequest(httpRequestBase);/*  w w w .j a v a 2 s.  c  o  m*/

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {
        if (_closeableHttpAsyncClient == null) {
            afterPropertiesSet();
        }

        Future<HttpResponse> future = null;

        if (!isNull(_login) && !isNull(_password)) {
            HttpClientContext httpClientContext = HttpClientContext.create();

            AuthCache authCache = new BasicAuthCache();

            AuthScheme authScheme = null;

            if (!isNull(_proxyHostName)) {
                authScheme = new BasicScheme(ChallengeState.PROXY);
            } else {
                authScheme = new BasicScheme(ChallengeState.TARGET);
            }

            authCache.put(httpHost, authScheme);

            httpClientContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, httpClientContext, null);
        } else {
            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, null);
        }

        HttpResponse httpResponse = future.get();

        StatusLine statusLine = httpResponse.getStatusLine();

        int statusCode = statusLine.getStatusCode();

        if (_logger.isTraceEnabled()) {
            _logger.trace("Server returned status " + statusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        if ((statusCode == HttpServletResponse.SC_NO_CONTENT)
                || (((httpEntity == null) || (httpEntity.getContentLength() == 0))
                        && _isStatus2XX(statusCode))) {

            return null;
        }

        String content = EntityUtils.toString(httpEntity, _CHARSET);

        if ((httpEntity.getContentType() != null) && _isApplicationJSONContentType(httpEntity)) {

            content = updateJSON(content);
        }

        if (_isStatus2XX(statusCode)) {
            return content;
        } else if ((statusCode == HttpServletResponse.SC_BAD_REQUEST)
                || (statusCode == HttpServletResponse.SC_FORBIDDEN)
                || (statusCode == HttpServletResponse.SC_METHOD_NOT_ALLOWED)
                || (statusCode == HttpServletResponse.SC_NOT_ACCEPTABLE)
                || (statusCode == HttpServletResponse.SC_NOT_FOUND)) {

            throw new JSONWebServiceInvocationException(content, statusCode);
        } else if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            throw new JSONWebServiceTransportException.AuthenticationFailure(
                    "Not authorized to access JSON web service");
        }

        throw new JSONWebServiceTransportException.CommunicationFailure("Server returned status " + statusCode,
                statusCode);
    } catch (ExecutionException ee) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ee);
    } catch (InterruptedException ie) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ie);
    } catch (IOException ioe) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ioe);
    } finally {
        httpRequestBase.releaseConnection();
    }
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the builder based on the request elements
 * /*from w  ww  .  j  a  va 2s .c  o m*/
 * @param requestConfigurationBuilder The builder to be set
 * @param authorization The authentication element of the request
 * @param proxy The proxy element of the request
 * @param urlHost The URL host of the request
 * @param urlPort The URL post of the request
 * @param urlProtocol The URL protocol of the request
 * @param httpClientBuilder The builder to be set
 * @return HTTPContext The HTTP context to be set
 */
private HttpContext setAuthorizations(final Builder requestConfigurationBuilder,
        final Authorization authorization, final Proxy proxy, final String urlHost, final int urlPort,
        final String urlProtocol, final HttpClientBuilder httpClientBuilder) {
    HttpContext httpContext = HttpClientContext.create();
    if (authorization != null) {
        if (authorization instanceof BasicDigestAuthorization) {
            final BasicDigestAuthorization castAuthorization = (BasicDigestAuthorization) authorization;

            final List<String> authPrefs = new ArrayList<>();
            if (castAuthorization.isBasic()) {
                authPrefs.add(AuthSchemes.BASIC);
            } else {
                authPrefs.add(AuthSchemes.DIGEST);
            }
            requestConfigurationBuilder.setTargetPreferredAuthSchemes(authPrefs);

            final String username = castAuthorization.getUsername();
            final String password = new String(castAuthorization.getPassword());
            String host = urlHost;
            if (isStringInputValid(castAuthorization.getHost())) {
                host = castAuthorization.getHost();
            }

            int port = urlPort;
            if (castAuthorization.getPort() != null) {
                port = castAuthorization.getPort();
            }

            String realm = AuthScope.ANY_REALM;
            if (isStringInputValid(castAuthorization.getRealm())) {
                realm = castAuthorization.getRealm();
            }

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(host, port, realm),
                    new UsernamePasswordCredentials(username, password));
            setProxyCrendentials(proxy, credentialsProvider);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

            if (castAuthorization.isPreemptive() || proxy != null) {
                final AuthCache authoriationCache = new BasicAuthCache();
                if (castAuthorization.isPreemptive()) {
                    AuthSchemeBase authorizationScheme = null;
                    if (castAuthorization.isBasic()) {
                        authorizationScheme = new BasicScheme(ChallengeState.TARGET);
                    } else {
                        authorizationScheme = new DigestScheme(ChallengeState.TARGET);
                    }
                    authoriationCache.put(new HttpHost(host, port, urlProtocol), authorizationScheme);
                }
                if (proxy != null) {
                    final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY);
                    authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme);
                }
                final HttpClientContext localContext = HttpClientContext.create();
                localContext.setAuthCache(authoriationCache);
                httpContext = localContext;
            }
        }
    } else if (proxy != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        setProxyCrendentials(proxy, credentialsProvider);
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

        // Make it preemptive
        if (proxy.hasCredentials()) {
            final AuthCache authoriationCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY);
            authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme);
            final HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authoriationCache);
            httpContext = localContext;
        }
    }

    return httpContext;
}