Example usage for org.apache.http.client CredentialsProvider setCredentials

List of usage examples for org.apache.http.client CredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider setCredentials.

Prototype

void setCredentials(AuthScope authscope, Credentials credentials);

Source Link

Document

Sets the Credentials credentials for the given authentication scope.

Usage

From source file:org.fcrepo.apix.registry.HttpClientFactory.java

/**
 * Construct a new HttpClient./*ww  w. ja  v a  2s  .  c o m*/
 *
 * @return HttpClient impl.
 */
public CloseableHttpClient getClient() {
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();

    final CredentialsProvider provider = new BasicCredentialsProvider();

    for (final AuthSpec authSpec : getAuthSpecs()) {
        LOG.debug("Using basic auth to {}://{}:{} with client", authSpec.scheme, authSpec.host, authSpec.port);
        final HttpHost host = new HttpHost(authSpec.host, authSpec.port, authSpec.scheme);

        provider.setCredentials(new AuthScope(host, AuthScope.ANY_REALM, authSpec.scheme),
                new UsernamePasswordCredentials(authSpec.username(), authSpec.passwd()));
    }

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            .addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest req, final HttpContext cxt)
                        throws HttpException, IOException {
                    if (!req.containsHeader(HttpHeaders.AUTHORIZATION)) {
                        final String[] hostInfo = req.getFirstHeader(HttpHeaders.HOST).getValue().split(":");
                        final Credentials creds = provider.getCredentials(new AuthScope(
                                new HttpHost(hostInfo[0],
                                        hostInfo.length > 1 ? Integer.valueOf(hostInfo[1]) : 80),
                                AuthScope.ANY_REALM, "http"));

                        if (creds != null) {
                            req.addHeader(HttpHeaders.AUTHORIZATION,
                                    "Basic " + Base64.getEncoder().encodeToString(
                                            String.format("%s:%s", creds.getUserPrincipal().getName(),
                                                    creds.getPassword()).getBytes()));
                            LOG.debug("Added auth header");
                        }
                    }
                }
            }).setDefaultCredentialsProvider(provider).build();
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare asynchronous connection./*w  w w .j ava  2s .co  m*/
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException
 */
public void prepareAsyncConnection() throws EWSHttpException {
    try {
        //ssl config
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);
        builder.setSchemePortResolver(new DefaultSchemePortResolver());

        EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger);
        builder.setSSLSocketFactory(factory);
        builder.setSslcontext(factory.getContext());

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials(getUserName(), getPassword(), "", getDomain()));
        builder.setDefaultCredentialsProvider(credsProvider);

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthSchemes.NTLM);
        rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        //

        builder.setDefaultRequestConfig(rcBuilder.build());

        //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects
        //create the client and execute requests
        client = builder.build();
        httpPostReq = new HttpPost(getUrl().toString());
        response = client.execute(httpPostReq);
    } catch (IOException e) {
        client = null;
        httpPostReq = null;
        throw new EWSHttpException("Unable to open connection to " + this.getUrl());
    } catch (Exception e) {
        client = null;
        httpPostReq = null;
        e.printStackTrace();
        throw new EWSHttpException("SSL problem " + this.getUrl());
    }
}

From source file:edu.ucsb.nceas.ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls uning this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 * @throws EZIDException if authentication fails for any reason
 *///from  ww w . j  av a 2 s.  co m
public void login(String username, String password) throws EZIDException {
    try {
        URI serviceUri = new URI(loginServiceEndpoint);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        HttpClientContext localcontext = HttpClientContext.create();
        localcontext.setAuthCache(authCache);
        localcontext.setCredentialsProvider(credsProvider);

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(loginServiceEndpoint);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        String msg = parseIdentifierResponse(message);
    } catch (URISyntaxException e) {
        throw new EZIDException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new EZIDException(e.getMessage());
    } catch (IOException e) {
        throw new EZIDException(e.getMessage());
    }
}

From source file:org.neo4j.jdbc.http.driver.CypherExecutor.java

private CredentialsProvider getCredentialsProvider(String host, Integer port, Properties properties) {
    if (properties.containsKey("password")) {
        String user = properties.getProperty("user", properties.getProperty("username", "neo4j"));
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user,
                properties.getProperty("password"));
        credsProvider.setCredentials(new AuthScope(host, port), credentials);
        return credsProvider;
    }// w  ww. ja v a 2 s .  c  o  m
    return null;
}

From source file:org.apache.nifi.processors.standard.util.HTTPUtils.java

public static void setProxy(final ProcessContext context, final HttpClientBuilder clientBuilder,
        final CredentialsProvider credentialsProvider) {
    // Set the proxy if specified
    final ProxyConfiguration proxyConfig = ProxyConfiguration.getConfiguration(context, () -> {
        if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) {
            final ProxyConfiguration componentProxyConfig = new ProxyConfiguration();
            final String host = context.getProperty(PROXY_HOST).getValue();
            final int port = context.getProperty(PROXY_PORT).asInteger();
            componentProxyConfig.setProxyType(Proxy.Type.HTTP);
            componentProxyConfig.setProxyServerHost(host);
            componentProxyConfig.setProxyServerPort(port);
            return componentProxyConfig;
        }/*from   w  w  w .  j  av a 2  s.  c  om*/
        return ProxyConfiguration.DIRECT_CONFIGURATION;
    });

    if (Proxy.Type.HTTP.equals(proxyConfig.getProxyType())) {
        final String host = proxyConfig.getProxyServerHost();
        final int port = proxyConfig.getProxyServerPort();
        clientBuilder.setProxy(new HttpHost(host, port));

        if (proxyConfig.hasCredential()) {
            final AuthScope proxyAuthScope = new AuthScope(host, port);
            final UsernamePasswordCredentials proxyCredential = new UsernamePasswordCredentials(
                    proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword());
            credentialsProvider.setCredentials(proxyAuthScope, proxyCredential);
        }
    }
}

From source file:com.bordercloud.sparql.Endpoint.java

private HashMap<String, HashMap> sendQueryPOSTwithAuth(String urlStr, String parameter, String query,
        String login, String password) throws EndpointException {

    int statusCode = 0;
    try {/*from w  w w  . ja v a2s  .  c  o m*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(login, password));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();
        try {
            HttpPost httpPost = new HttpPost(urlStr);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair(parameter, query));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            CloseableHttpResponse response2 = httpclient.execute(httpPost);

            try {
                //System.out.println(response2.getStatusLine());
                statusCode = response2.getStatusLine().getStatusCode();
                if (statusCode < 200 || statusCode >= 300) {
                    throw new EndpointException(this, response2.getStatusLine().toString());
                }
                HttpEntity entity2 = response2.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                ////System.out.println(EntityUtils.toString(entity2));

                _response = EntityUtils.toString(entity2);
                //EntityUtils.consume(entity2);
            } finally {
                response2.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

    return getResult();
}

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java

private CredentialsProvider checkBasicCredentials() {
    String user = properties.get(USER);
    String password = properties.get(PASS);
    if (!isEmpty(user)) {
        if (!isEmpty(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
            return credentialsProvider;
        } else {//w w w  .  j av a  2 s  .c o m
            log.warnf("User [%s] without password ", user);
        }
    }
    return null;
}

From source file:org.kie.server.integrationtests.shared.KieServerBaseIntegrationTest.java

protected ClientRequest newRequest(String uriString) {
    URI uri;/*from  w  w  w. j av a2s .c  o m*/
    try {
        uri = new URI(uriString);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Malformed request URI was specified: '" + uriString + "'!", e);
    }
    if (httpClient == null) {
        if (TestConfig.isLocalServer()) {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                    .setConnectTimeout(1000).setSocketTimeout(1000).build();
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        } else {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(2000)
                    .setConnectTimeout(2000).setSocketTimeout(2000).build();
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                    new UsernamePasswordCredentials(TestConfig.getUsername(), TestConfig.getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
                    .setDefaultCredentialsProvider(credentialsProvider).build();
        }
    }
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient);
    return new ClientRequest(uriString, executor);
}

From source file:com.ibm.watson.app.common.util.http.HttpClientBuilder.java

public static CloseableHttpClient buildDefaultHttpClient(Credentials cred) {

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    RequestConfig defaultRequestConfig;/*from   www .j av  a  2s  .co m*/

    //private DefaultHttpClient client;
    connManager.setMaxTotal(200);
    connManager.setDefaultMaxPerRoute(50);
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        // Create a registry of custom connection socket factories for supported
        // protocol schemes.
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(builder.build())).build();
    } catch (Exception e) {
        logger.warn(MessageKey.AQWEGA02000W_unable_init_ssl_context.getMessage(), e);
    }
    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(
                    Arrays.asList(AuthSchemes.BASIC, AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setAuthenticationEnabled(true).build();

    if (cred != null)
        credentialsProvider.setCredentials(AuthScope.ANY, cred);

    return HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(defaultRequestConfig)
            .build();
}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Make the DOI obsolete by setting the EZID metadata field "_status" to
 * "unavailable"./* w w  w.  j  av  a2  s  .  c om*/
 * 
 * @param doi The DOI to obsolete
 * @throws EzidException
 */
public void obsoleteDoi(String doi) throws EzidException {

    HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // 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(httpHost, basicAuth);

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

    String url = this.getEzidUrl("/id/" + doi);

    StringBuffer metadata = new StringBuffer("");
    metadata.append("_status: unavailable | withdrawn by author\n");

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Content-type", "text/plain");
    HttpEntity stringEntity = null;
    Integer statusCode = null;
    String entityString = null;

    try {
        stringEntity = new StringEntity(metadata.toString());
        httpPost.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpHost, httpPost, context);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpEntity httpEntity = httpResponse.getEntity();
        entityString = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    logger.info("obsoleteDoi: " + entityString);

    if (statusCode != HttpStatus.SC_OK) {
        String gripe = "DOI obsoletion failed for: " + doi;
        throw new EzidException(gripe);
    }

}