Search in sources :

Example 11 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project openhab1-addons by openhab.

the class Tr064Comm method createTr064HttpClient.

/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
    credp).setDefaultRequestConfig(// set the request config specifying timeout
    rc).build();
    return hc;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 12 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project ats-framework by Axway.

the class HttpClient method setupAuthentication.

/**
     * Set up authentication for HTTP Basic/HTTP Digest/SPNEGO.
     *
     * @param httpClientBuilder The client builder
     * @return The context
     * @throws HttpException
     */
private HttpClientContext setupAuthentication(HttpClientBuilder httpClientBuilder) throws HttpException {
    HttpClientContext localContext = null;
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
    httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    if (authType == AuthType.always) {
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL uri = null;
        try {
            uri = new URL(url);
        } catch (MalformedURLException e) {
            throw new HttpException("Exception occurred creating URL from '" + url + "'.", e);
        }
        HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getProtocol());
        authCache.put(target, basicAuth);
        // Add AuthCache to the execution context
        localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);
    } else {
        if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) {
            GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile);
            AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName, kerberosServicePrincipalType);
            final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, nsf).build();
            httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        }
    }
    return localContext;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) MalformedURLException(java.net.MalformedURLException) 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) SPNegoSchemeFactory(com.axway.ats.core.gss.spnego.SPNegoSchemeFactory) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) GssClient(com.axway.ats.core.gss.GssClient) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider)

Example 13 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project opennms by OpenNMS.

the class RestSessionIT method queryUri.

private Header[] queryUri(final String uri, final String header) throws IOException {
    final HttpGet httpGet = new HttpGet(getBaseUrl() + uri);
    final HttpHost targetHost = new HttpHost(httpGet.getURI().getHost(), httpGet.getURI().getPort(), httpGet.getURI().getScheme());
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin"));
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    final CloseableHttpResponse closeableHttpResponse = HttpClients.createDefault().execute(targetHost, httpGet, context);
    closeableHttpResponse.close();
    return closeableHttpResponse.getHeaders(header);
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) HttpGet(org.apache.http.client.methods.HttpGet) AuthScope(org.apache.http.auth.AuthScope) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) AuthCache(org.apache.http.client.AuthCache) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) 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 14 with BasicAuthCache

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

the class HTTPHC4Impl method executeRequest.

/**
     * Execute request either as is or under PrivilegedAction 
     * if a Subject is available for url
     * @param httpClient the {@link CloseableHttpClient} to be used to execute the httpRequest
     * @param httpRequest the {@link HttpRequest} to be executed
     * @param localContext th {@link HttpContext} to be used for execution
     * @param url the target url (will be used to look up a possible subject for the execution)
     * @return the result of the execution of the httpRequest
     * @throws IOException
     * @throws ClientProtocolException
     */
private CloseableHttpResponse executeRequest(final CloseableHttpClient httpClient, final HttpRequestBase httpRequest, final HttpContext localContext, final URL url) throws IOException, ClientProtocolException {
    AuthManager authManager = getAuthManager();
    if (authManager != null) {
        Subject subject = authManager.getSubjectForUrl(url);
        if (subject != null) {
            try {
                return Subject.doAs(subject, (PrivilegedExceptionAction<CloseableHttpResponse>) () -> httpClient.execute(httpRequest, localContext));
            } catch (PrivilegedActionException e) {
                log.error("Can't execute httpRequest with subject: {}", subject, e);
                throw new RuntimeException("Can't execute httpRequest with subject:" + subject, e);
            }
        }
        if (BASIC_AUTH_PREEMPTIVE) {
            Authorization authorization = authManager.getAuthForURL(url);
            if (authorization != null && Mechanism.BASIC_DIGEST.equals(authorization.getMechanism())) {
                HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
                // 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(target, basicAuth);
                // Add AuthCache to the execution context
                localContext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
            }
        }
    }
    return httpClient.execute(httpRequest, localContext);
}
Also used : Authorization(org.apache.jmeter.protocol.http.control.Authorization) BasicScheme(org.apache.http.impl.auth.BasicScheme) AuthManager(org.apache.jmeter.protocol.http.control.AuthManager) PrivilegedActionException(java.security.PrivilegedActionException) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Subject(javax.security.auth.Subject)

Aggregations

BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)14 AuthCache (org.apache.http.client.AuthCache)13 BasicScheme (org.apache.http.impl.auth.BasicScheme)12 HttpHost (org.apache.http.HttpHost)11 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)9 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)9 AuthScope (org.apache.http.auth.AuthScope)7 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)7 CredentialsProvider (org.apache.http.client.CredentialsProvider)7 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 IOException (java.io.IOException)4 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 ClientProtocolException (org.apache.http.client.ClientProtocolException)2 HttpGet (org.apache.http.client.methods.HttpGet)2 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)2 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)2 GssClient (com.axway.ats.core.gss.GssClient)1 SPNegoSchemeFactory (com.axway.ats.core.gss.spnego.SPNegoSchemeFactory)1