Search in sources :

Example 61 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project tutorials by eugenp.

the class HttpClientPostingLiveTest method whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect.

@Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
    final CloseableHttpClient client = HttpClients.createDefault();
    final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
    httpPost.setEntity(new StringEntity("test post"));
    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
    httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
    final CloseableHttpResponse response = client.execute(httpPost);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Test(org.junit.Test)

Example 62 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme 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 63 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme 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 64 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme 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)

Example 65 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project jbpm by kiegroup.

the class RESTWorkItemHandler method doRequestWithAuthorization.

protected HttpResponse doRequestWithAuthorization(HttpClient httpclient, HttpRequestBase httpMethod, Map<String, Object> params, AuthenticationType type) {
    if (type == null || type == AuthenticationType.NONE) {
        try {
            return httpclient.execute(httpMethod);
        } catch (Exception e) {
            throw new RuntimeException("Could not execute request [" + httpMethod.getMethod() + "] " + httpMethod.getURI(), e);
        }
    }
    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) {
        HttpHost targetHost = new HttpHost(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), httpMethod.getURI().getScheme());
        ((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(u, p));
        // 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(targetHost, basicAuth);
        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        try {
            return httpclient.execute(targetHost, httpMethod, localcontext);
        } catch (Exception e) {
            throw new RuntimeException("Could not execute request [" + httpMethod.getMethod() + "] " + httpMethod.getURI(), e);
        }
    } else if (type == AuthenticationType.FORM_BASED) {
        String authUrlStr = (String) params.get(PARAM_AUTHURL);
        if (authUrlStr == null) {
            authUrlStr = authUrl;
        }
        if (authUrlStr == null) {
            throw new IllegalArgumentException("Could not find authentication url");
        }
        try {
            httpclient.execute(httpMethod);
        } catch (IOException e) {
            throw new RuntimeException("Could not execute request for form-based authentication", e);
        } finally {
            httpMethod.releaseConnection();
        }
        HttpPost authMethod = new HttpPost(authUrlStr);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", u));
        nvps.add(new BasicNameValuePair("j_password", p));
        authMethod.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        try {
            httpclient.execute(authMethod);
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize form-based authentication", e);
        } finally {
            authMethod.releaseConnection();
        }
        try {
            return httpclient.execute(httpMethod);
        } catch (Exception e) {
            throw new RuntimeException("Could not execute request [" + httpMethod.getMethod() + "] " + httpMethod.getURI(), e);
        }
    } else {
        throw new RuntimeException("Unknown AuthenticationType " + type);
    }
}
Also used : 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) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) IOException(java.io.IOException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) 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

BasicScheme (org.apache.http.impl.auth.BasicScheme)82 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)57 CredentialsProvider (org.apache.http.client.CredentialsProvider)48 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)47 AuthCache (org.apache.http.client.AuthCache)46 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)46 HttpHost (org.apache.http.HttpHost)45 AuthScope (org.apache.http.auth.AuthScope)38 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)32 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)25 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)24 HttpGet (org.apache.http.client.methods.HttpGet)23 URI (java.net.URI)20 Test (org.junit.Test)18 IOException (java.io.IOException)13 Credentials (org.apache.http.auth.Credentials)13 HttpResponse (org.apache.http.HttpResponse)9 HttpPost (org.apache.http.client.methods.HttpPost)9 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)9 Header (org.apache.http.Header)8