Example usage for org.apache.http.auth ChallengeState TARGET

List of usage examples for org.apache.http.auth ChallengeState TARGET

Introduction

In this page you can find the example usage for org.apache.http.auth ChallengeState TARGET.

Prototype

ChallengeState TARGET

To view the source code for org.apache.http.auth ChallengeState TARGET.

Click Source Link

Usage

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  . java 2s  .  c  om

    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:org.switchyard.component.http.OutboundHandler.java

/**
 * Start lifecycle.//w  w  w . j  av a  2 s . 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.switchyard.component.resteasy.util.ClientInvoker.java

/**
 * Create a RESTEasy invoker client./* w  ww .  j  av  a2s. c om*/
 *
 * @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 ww  . j  a va 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 w w . j  a  v a 2 s  . 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;
}