Search in sources :

Example 36 with BasicAuthCache

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

the class HttpSenderBase method setupAuthentication.

private void setupAuthentication(CredentialFactory user_cf, CredentialFactory proxyCredentials, HttpHost proxy, Builder requestConfigBuilder) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    if (StringUtils.isNotEmpty(user_cf.getUsername()) || StringUtils.isNotEmpty(getTokenEndpoint())) {
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), getCredentials());
        AuthenticationScheme preferredAuthenticationScheme = getPreferredAuthenticationScheme();
        requestConfigBuilder.setTargetPreferredAuthSchemes(Arrays.asList(preferredAuthenticationScheme.getSchemeName()));
        requestConfigBuilder.setAuthenticationEnabled(true);
        if (preferredAuthenticationScheme == AuthenticationScheme.OAUTH) {
            CredentialFactory client_cf = new CredentialFactory(getClientAuthAlias(), getClientId(), getClientSecret());
            OAuthAccessTokenManager accessTokenManager = new OAuthAccessTokenManager(getTokenEndpoint(), getScope(), client_cf, StringUtils.isEmpty(user_cf.getUsername()), this, getTokenExpiry());
            httpClientContext.setAttribute(OAuthAuthenticationScheme.ACCESSTOKEN_MANAGER_KEY, accessTokenManager);
            httpClientBuilder.setTargetAuthenticationStrategy(new OAuthPreferringAuthenticationStrategy());
        }
    }
    if (proxy != null) {
        AuthScope scope = new AuthScope(proxy, proxyRealm, AuthScope.ANY_SCHEME);
        if (StringUtils.isNotEmpty(proxyCredentials.getUsername())) {
            Credentials credentials = new UsernamePasswordCredentials(proxyCredentials.getUsername(), proxyCredentials.getPassword());
            credentialsProvider.setCredentials(scope, credentials);
        }
        if (prefillProxyAuthCache()) {
            requestConfigBuilder.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
            AuthCache authCache = httpClientContext.getAuthCache();
            if (authCache == null)
                authCache = new BasicAuthCache();
            authCache.put(proxy, new BasicScheme());
            httpClientContext.setAuthCache(authCache);
        }
    }
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
Also used : AuthenticationScheme(nl.nn.adapterframework.http.authentication.AuthenticationScheme) OAuthAuthenticationScheme(nl.nn.adapterframework.http.authentication.OAuthAuthenticationScheme) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) OAuthPreferringAuthenticationStrategy(nl.nn.adapterframework.http.authentication.OAuthPreferringAuthenticationStrategy) CredentialFactory(nl.nn.adapterframework.util.CredentialFactory) AuthScope(org.apache.http.auth.AuthScope) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) OAuthAccessTokenManager(nl.nn.adapterframework.http.authentication.OAuthAccessTokenManager) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 37 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project zm-mailbox by Zimbra.

the class WebDavClient method setCredential.

public void setCredential(String user, String pass, String targetUrl) {
    mUsername = user;
    mPassword = pass;
    Credentials cred = new UsernamePasswordCredentials(mUsername, mPassword);
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, cred);
    HttpHost targetHost = new HttpHost(targetUrl);
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());
    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);
}
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) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 38 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project zm-mailbox by Zimbra.

the class FeedManager method retrieveRemoteData.

private static RemoteDataInfo retrieveRemoteData(String url, Folder.SyncData fsd) throws ServiceException, HttpException, IOException {
    assert !Strings.isNullOrEmpty(url);
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(clientBuilder);
    // cannot set connection timeout because it'll affect all HttpClients associated with the conn mgr.
    // see comments in ZimbraHttpConnectionManager
    // client.setConnectionTimeout(10000);
    SocketConfig config = SocketConfig.custom().setSoTimeout(60000).build();
    clientBuilder.setDefaultSocketConfig(config);
    ConnectionConfig connConfig = ConnectionConfig.custom().setCharset(Charset.forName(MimeConstants.P_CHARSET_UTF8)).build();
    clientBuilder.setDefaultConnectionConfig(connConfig);
    HttpGet get = null;
    BufferedInputStream content = null;
    long lastModified = 0;
    String expectedCharset = MimeConstants.P_CHARSET_UTF8;
    int redirects = 0;
    int statusCode = HttpServletResponse.SC_NOT_FOUND;
    try {
        do {
            String lcurl = url.toLowerCase();
            if (lcurl.startsWith("webcal:")) {
                url = "http:" + url.substring(7);
            } else if (lcurl.startsWith("feed:")) {
                url = "http:" + url.substring(5);
            } else if (!lcurl.startsWith("http:") && !lcurl.startsWith("https:")) {
                throw ServiceException.INVALID_REQUEST("url must begin with http: or https:", null);
            }
            // Add AuthCache to the execution context
            HttpClientContext context = HttpClientContext.create();
            URIBuilder httpurl;
            try {
                httpurl = new URIBuilder(url);
            } catch (URISyntaxException e1) {
                throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, e1);
            }
            // validate target address (also handles followed `location` header addresses)
            if (isBlockedFeedAddress(httpurl)) {
                ZimbraLog.misc.info("Feed ip address blocked: %s. See localconfig for comma-separated ip list configuration: " + "zimbra_feed_manager_blacklist, zimbra_feed_manager_whitelist", url);
                throw ServiceException.INVALID_REQUEST(String.format("Address for feed is blocked: %s. See mailbox logs for details.", url), null);
            }
            // username and password are encoded in the URL as http://user:pass@host/...
            if (url.indexOf('@') != -1) {
                if (httpurl.getUserInfo() != null) {
                    String user = httpurl.getUserInfo();
                    if (user.indexOf('%') != -1) {
                        try {
                            user = URLDecoder.decode(user, "UTF-8");
                        } catch (OutOfMemoryError e) {
                            Zimbra.halt("out of memory", e);
                        } catch (Throwable t) {
                        }
                    }
                    int index = user.indexOf(':');
                    String userName = user.substring(0, index);
                    String password = user.substring(index + 1);
                    CredentialsProvider provider = new BasicCredentialsProvider();
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    clientBuilder.setDefaultCredentialsProvider(provider);
                    // 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(new HttpHost(httpurl.getHost()), basicAuth);
                    // Add AuthCache to the execution context
                    context.setCredentialsProvider(provider);
                    context.setAuthCache(authCache);
                }
            }
            try {
                get = new HttpGet(url);
            } catch (OutOfMemoryError e) {
                Zimbra.halt("out of memory", e);
                return null;
            } catch (Throwable t) {
                ZimbraLog.misc.warnQuietly(String.format("invalid url for feed: %s", url), t);
                throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, null);
            }
            DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            clientBuilder.setRedirectStrategy(redirectStrategy);
            get.addHeader("User-Agent", HTTP_USER_AGENT);
            get.addHeader("Accept", HTTP_ACCEPT);
            if (fsd != null && fsd.getLastSyncDate() > 0) {
                String lastSyncAt = DateUtils.formatDate(new Date(fsd.getLastSyncDate()));
                get.addHeader("If-Modified-Since", lastSyncAt);
            }
            HttpClient client = clientBuilder.build();
            HttpResponse response = HttpClientUtil.executeMethod(client, get, context);
            Header locationHeader = response.getFirstHeader("location");
            if (locationHeader != null) {
                // update our target URL and loop again to do another HTTP GET
                url = locationHeader.getValue();
                get.releaseConnection();
            } else {
                statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpServletResponse.SC_OK) {
                    Header contentEncoding = response.getFirstHeader("Content-Encoding");
                    InputStream respInputStream = response.getEntity().getContent();
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().indexOf("gzip") != -1) {
                            respInputStream = new GZIPInputStream(respInputStream);
                        }
                    }
                    content = new BufferedInputStream(respInputStream);
                    org.apache.http.entity.ContentType contentType = org.apache.http.entity.ContentType.getOrDefault(response.getEntity());
                    if (contentType != null && contentType.getCharset() != null) {
                        expectedCharset = contentType.getCharset().name();
                    }
                    Header lastModHdr = response.getFirstHeader("Last-Modified");
                    if (lastModHdr == null) {
                        lastModHdr = response.getFirstHeader("Date");
                    }
                    if (lastModHdr != null) {
                        Date d = DateUtils.parseDate(lastModHdr.getValue());
                        lastModified = d.getTime();
                    } else {
                        lastModified = System.currentTimeMillis();
                    }
                } else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
                    ZimbraLog.misc.debug("Remote data at " + url + " not modified since last sync");
                    return new RemoteDataInfo(statusCode, redirects, null, expectedCharset, lastModified);
                } else {
                    throw ServiceException.RESOURCE_UNREACHABLE(response.getStatusLine().toString(), null);
                }
                break;
            }
        } while (++redirects <= MAX_REDIRECTS);
    } catch (ServiceException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (HttpException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (IOException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    }
    RemoteDataInfo rdi = new RemoteDataInfo(statusCode, redirects, content, expectedCharset, lastModified);
    rdi.setGetMethod(get);
    return rdi;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URISyntaxException(java.net.URISyntaxException) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) HttpHost(org.apache.http.HttpHost) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy) HttpException(org.apache.http.HttpException) ConnectionConfig(org.apache.http.config.ConnectionConfig) BasicScheme(org.apache.http.impl.auth.BasicScheme) SocketConfig(org.apache.http.config.SocketConfig) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) 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) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) Date(java.util.Date) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) ServiceException(com.zimbra.common.service.ServiceException) HttpClient(org.apache.http.client.HttpClient)

Example 39 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project qpid-broker-j by apache.

the class QpidRestAPIQueueCreator method getHttpClientContext.

private HttpClientContext getHttpClientContext(final HttpHost management) {
    final BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(management, new BasicScheme());
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache)

Example 40 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 void setupAuthentication(HttpClientBuilder httpClientBuilder) throws HttpException {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
    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();
        HttpHost target = new HttpHost(host, port, isOverSsl ? "https" : "http");
        authCache.put(target, basicAuth);
        // Add AuthCache to the execution context
        httpContext.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);
        }
    }
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) GssClient(com.axway.ats.core.gss.GssClient) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) SPNegoSchemeFactory(com.axway.ats.core.gss.spnego.SPNegoSchemeFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

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