Search in sources :

Example 41 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project acceptance-test-harness by jenkinsci.

the class HttpUtils method buildHttpClientContext.

public static HttpClientContext buildHttpClientContext(@Nonnull URL url, @CheckForNull Credentials credentials) {
    HttpClientContext context = HttpClientContext.create();
    if (credentials != null) {
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());
        // Add AuthCache to the execution context
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);
    }
    return context;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) AuthCache(org.apache.http.client.AuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider)

Example 42 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project tutorials by eugenp.

the class HttpClientAuthLiveTest method context.

private HttpContext context() {
    final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
    // Create AuthCache instance
    final AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    authCache.put(targetHost, new BasicScheme());
    // Add AuthCache to the execution context
    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 43 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project nuxeo-filesystem-connectors by nuxeo.

the class WebDavClientTest method setUpClass.

@BeforeClass
public static void setUpClass() {
    // credentials
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
    // AuthCache instance for preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost("localhost", WebDavServerFeature.PORT), new BasicScheme());
    // create context
    context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);
    // create client
    client = HttpClients.createDefault();
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BeforeClass(org.junit.BeforeClass)

Example 44 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project fabric-sdk-java by hyperledger.

the class HFCAClient method httpPost.

/**
 * Http Post Request.
 *
 * @param url         Target URL to POST to.
 * @param body        Body to be sent with the post.
 * @param credentials Credentials to use for basic auth.
 * @return Body of post returned.
 * @throws Exception
 */
String httpPost(String url, String body, UsernamePasswordCredentials credentials) throws Exception {
    logger.debug(format("httpPost %s, body:%s", url, body));
    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    CredentialsProvider provider = null;
    if (credentials != null) {
        provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }
    HttpClient client = httpClientBuilder.build();
    HttpPost httpPost = new HttpPost(url);
    AuthCache authCache = new BasicAuthCache();
    HttpHost targetHost = new HttpHost(httpPost.getURI().getHost(), httpPost.getURI().getPort());
    if (credentials != null) {
        authCache.put(targetHost, new BasicScheme());
    }
    final HttpClientContext context = HttpClientContext.create();
    if (null != provider) {
        context.setCredentialsProvider(provider);
    }
    if (credentials != null) {
        context.setAuthCache(authCache);
    }
    httpPost.setEntity(new StringEntity(body));
    if (credentials != null) {
        httpPost.addHeader(new BasicScheme().authenticate(credentials, httpPost, context));
    }
    HttpResponse response = client.execute(httpPost, context);
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    logger.trace(format("httpPost %s  sending...", url));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("httpPost %s  responseBody %s", url, responseBody));
    if (status >= 400) {
        Exception e = new Exception(format("POST request to %s  with request body: %s, " + "failed with status code: %d. Response: %s", url, body, status, responseBody));
        logger.error(e.getMessage());
        throw e;
    }
    logger.debug(format("httpPost Status: %d returning: %s ", status, responseBody));
    return responseBody;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) InvalidArgumentException(org.hyperledger.fabric_ca.sdk.exception.InvalidArgumentException) URISyntaxException(java.net.URISyntaxException) RegistrationException(org.hyperledger.fabric_ca.sdk.exception.RegistrationException) KeyStoreException(java.security.KeyStoreException) AffiliationException(org.hyperledger.fabric_ca.sdk.exception.AffiliationException) GenerateCRLException(org.hyperledger.fabric_ca.sdk.exception.GenerateCRLException) KeyManagementException(java.security.KeyManagementException) IdentityException(org.hyperledger.fabric_ca.sdk.exception.IdentityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EnrollmentException(org.hyperledger.fabric_ca.sdk.exception.EnrollmentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RevocationException(org.hyperledger.fabric_ca.sdk.exception.RevocationException) ParseException(org.apache.http.ParseException) MalformedURLException(java.net.MalformedURLException) InfoException(org.hyperledger.fabric_ca.sdk.exception.InfoException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) HTTPException(org.hyperledger.fabric_ca.sdk.exception.HTTPException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient)

Example 45 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project jbpm by kiegroup.

the class RESTWorkItemHandler method doRequestWithAuthorization.

/**
 * This method does the actual request, including the setup for authorization.
 * </p>
 * It is <b>not</b> responsible for cleaning up after the last request that it does.
 * </p>
 * It <i>is</i> responsible for cleaning up after all previous request, such as for form-based authentication, that happen.
 * @param httpclient The {@link HttpClient} instance
 * @param requestBuilder The {@link RequestBuilder} instance
 * @param params The parameters that may be needed for authentication
 * @return A {@link HttpResponse} instance from which we can extract the content
 */
protected HttpResponse doRequestWithAuthorization(HttpClient httpclient, RequestBuilder requestBuilder, Map<String, Object> params, AuthenticationType type) {
    // no authorization
    if (type == null || type == AuthenticationType.NONE) {
        HttpUriRequest request = requestBuilder.build();
        try {
            return httpclient.execute(request);
        } catch (Exception e) {
            throw new RuntimeException("Could not execute request [" + request.getMethod() + "] " + request.getURI(), e);
        }
    }
    // user/password
    String u = (String) params.get(PARAM_USERNAME);
    String p = (String) params.get(PARAM_PASSWORD);
    if (u == null || p == null) {
        u = this.username;
        p = this.password;
    }
    if (u == null) {
        throw new IllegalArgumentException("Could not find username");
    }
    if (p == null) {
        throw new IllegalArgumentException("Could not find password");
    }
    if (type == AuthenticationType.BASIC) {
        // basic auth
        URI requestUri = requestBuilder.getUri();
        HttpHost targetHost = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme());
        // Create AuthCache instance and add it: so that HttpClient thinks that it has already queried (as per the HTTP spec)
        // - generate BASIC scheme object and add it to the local auth cache
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        // - add AuthCache to the execution context:
        HttpClientContext clientContext = HttpClientContext.create();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(// specify host and port, since that is safer/more secure
        new AuthScope(requestUri.getHost(), requestUri.getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(u, p));
        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
        // - execute request
        HttpUriRequest request = requestBuilder.build();
        try {
            return httpclient.execute(targetHost, request, clientContext);
        } catch (Exception e) {
            throw new RuntimeException("Could not execute request with preemptive authentication [" + request.getMethod() + "] " + request.getURI(), e);
        }
    } else if (type == AuthenticationType.FORM_BASED) {
        // form auth
        // 1. do initial request to trigger authentication
        HttpUriRequest request = requestBuilder.build();
        int statusCode = -1;
        try {
            HttpResponse initialResponse = httpclient.execute(request);
            statusCode = initialResponse.getStatusLine().getStatusCode();
        } catch (IOException e) {
            throw new RuntimeException("Could not execute request for form-based authentication", e);
        } finally {
            // weird, but this is the method that releases resources, including the connection
            request.abort();
        }
        // See: www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
        if (statusCode != HttpStatus.SC_UNAUTHORIZED) {
            logger.error("Expected form authentication request with status {} but status on response is {}: proceeding anyways", HttpStatus.SC_UNAUTHORIZED, statusCode);
        }
        // 2. do POST form request to authentiate
        String authUrlStr = (String) params.get(PARAM_AUTHURL);
        if (authUrlStr == null) {
            authUrlStr = authUrl;
        }
        if (authUrlStr == null) {
            throw new IllegalArgumentException("Could not find authentication url");
        }
        HttpPost authMethod = new HttpPost(authUrlStr);
        List<NameValuePair> formParams = new ArrayList<NameValuePair>(2);
        formParams.add(new BasicNameValuePair("j_username", u));
        formParams.add(new BasicNameValuePair("j_password", p));
        UrlEncodedFormEntity formEntity;
        try {
            formEntity = new UrlEncodedFormEntity(formParams);
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Could not encode authentication parameters into request body", uee);
        }
        authMethod.setEntity(formEntity);
        try {
            httpclient.execute(authMethod);
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize form-based authentication", e);
        } finally {
            authMethod.releaseConnection();
        }
        // 3. rebuild request and execute
        request = requestBuilder.build();
        try {
            return httpclient.execute(request);
        } catch (Exception e) {
            throw new RuntimeException("Could not execute request [" + request.getMethod() + "] " + request.getURI(), e);
        }
    } else {
        throw new RuntimeException("Unknown AuthenticationType " + type);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URI(java.net.URI) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.http.HttpHost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) AuthScope(org.apache.http.auth.AuthScope) List(java.util.List) ArrayList(java.util.ArrayList)

Aggregations

BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)55 AuthCache (org.apache.http.client.AuthCache)49 BasicScheme (org.apache.http.impl.auth.BasicScheme)48 HttpHost (org.apache.http.HttpHost)39 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)36 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)33 CredentialsProvider (org.apache.http.client.CredentialsProvider)33 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)32 AuthScope (org.apache.http.auth.AuthScope)27 IOException (java.io.IOException)14 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)14 URI (java.net.URI)10 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)10 HttpGet (org.apache.http.client.methods.HttpGet)10 HttpResponse (org.apache.http.HttpResponse)9 HttpPost (org.apache.http.client.methods.HttpPost)7 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)7 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)7 File (java.io.File)6 URISyntaxException (java.net.URISyntaxException)6