Search in sources :

Example 6 with BasicCredentialsProvider

use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project mercury by yellow013.

the class ClientPreemptiveDigestAuthentication method main.

public static void main(final String[] args) throws Exception {
    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
        final HttpHost target = new HttpHost("http", "httpbin.org", 80);
        final HttpClientContext localContext = HttpClientContext.create();
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials("user", "passwd".toCharArray()));
        localContext.setCredentialsProvider(credentialsProvider);
        final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
        System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
        for (int i = 0; i < 3; i++) {
            try (final CloseableHttpResponse response = httpclient.execute(target, httpget, localContext)) {
                System.out.println("----------------------------------------");
                System.out.println(response.getCode() + " " + response.getReasonPhrase());
                EntityUtils.consume(response.getEntity());
                final AuthExchange authExchange = localContext.getAuthExchange(target);
                if (authExchange != null) {
                    final AuthScheme authScheme = authExchange.getAuthScheme();
                    if (authScheme instanceof DigestScheme) {
                        final DigestScheme digestScheme = (DigestScheme) authScheme;
                        System.out.println("Nonce: " + digestScheme.getNonce() + "; count: " + digestScheme.getNounceCount());
                    }
                }
            }
        }
    }
}
Also used : DigestScheme(org.apache.hc.client5.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) AuthExchange(org.apache.hc.client5.http.auth.AuthExchange) HttpHost(org.apache.hc.core5.http.HttpHost) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) AuthScope(org.apache.hc.client5.http.auth.AuthScope) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) AuthScheme(org.apache.hc.client5.http.auth.AuthScheme)

Example 7 with BasicCredentialsProvider

use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project webdrivermanager by bonigarcia.

the class HttpClient method createBasicCredentialsProvider.

private final Optional<BasicCredentialsProvider> createBasicCredentialsProvider(String proxy, String proxyUser, String proxyPass, HttpHost proxyHost) throws MalformedURLException, UnsupportedEncodingException {
    Optional<URL> proxyUrl = determineProxyUrl(proxy);
    if (!proxyUrl.isPresent()) {
        return empty();
    }
    String username = null;
    String password = null;
    // apply env value
    String userInfo = proxyUrl.get().getUserInfo();
    if (userInfo != null) {
        StringTokenizer st = new StringTokenizer(userInfo, ":");
        username = st.hasMoreTokens() ? decode(st.nextToken(), UTF_8.name()) : null;
        password = st.hasMoreTokens() ? decode(st.nextToken(), UTF_8.name()) : null;
    }
    String envProxyUser = getenv("HTTPS_PROXY_USER");
    String envProxyPass = getenv("HTTPS_PROXY_PASS");
    username = (envProxyUser != null) ? envProxyUser : username;
    password = (envProxyPass != null) ? envProxyPass : password;
    // apply option value
    username = isNullOrEmpty(proxyUser) ? username : proxyUser;
    password = isNullOrEmpty(proxyPass) ? password : proxyPass;
    if (username == null) {
        return empty();
    }
    String ntlmUsername = username;
    String ntlmDomain = null;
    int index = username.indexOf('\\');
    if (index > 0) {
        ntlmDomain = username.substring(0, index);
        ntlmUsername = username.substring(index + 1);
    }
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    AuthScope authScope = new AuthScope(proxyHost, null, NTLM);
    char[] passwd = (password == null) ? new char[0] : password.toCharArray();
    Credentials creds = new NTCredentials(ntlmUsername, passwd, getWorkstation(), ntlmDomain);
    credentialsProvider.setCredentials(authScope, creds);
    authScope = new AuthScope(proxyHost.getHostName(), proxyHost.getPort());
    creds = new UsernamePasswordCredentials(username, passwd);
    credentialsProvider.setCredentials(authScope, creds);
    return Optional.of(credentialsProvider);
}
Also used : StringTokenizer(java.util.StringTokenizer) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) AuthScope(org.apache.hc.client5.http.auth.AuthScope) URL(java.net.URL) Credentials(org.apache.hc.client5.http.auth.Credentials) NTCredentials(org.apache.hc.client5.http.auth.NTCredentials) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) NTCredentials(org.apache.hc.client5.http.auth.NTCredentials) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Example 8 with BasicCredentialsProvider

use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project wiremock by wiremock.

the class HttpClientFactory method createClient.

public static CloseableHttpClient createClient(int maxConnections, int timeoutMilliseconds, ProxySettings proxySettings, KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates, final List<String> trustedHosts, boolean useSystemProperties) {
    HttpClientBuilder builder = HttpClientBuilder.create().disableAuthCaching().disableAutomaticRetries().disableCookieManagement().disableRedirectHandling().disableContentCompression().setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create().setMaxConnPerRoute(maxConnections).setMaxConnTotal(maxConnections).setValidateAfterInactivity(// TODO Verify duration
    TimeValue.ofSeconds(5)).setConnectionFactory(new ManagedHttpClientConnectionFactory(null, CharCodingConfig.custom().setCharset(UTF_8).build(), null)).build()).setDefaultRequestConfig(RequestConfig.custom().setResponseTimeout(Timeout.ofMilliseconds(timeoutMilliseconds)).build()).setConnectionReuseStrategy((request, response, context) -> false).setKeepAliveStrategy((response, context) -> TimeValue.ZERO_MILLISECONDS);
    if (useSystemProperties) {
        builder.useSystemProperties();
    }
    if (proxySettings != NO_PROXY) {
        HttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());
        builder.setProxy(proxyHost);
        if (!isEmpty(proxySettings.getUsername()) && !isEmpty(proxySettings.getPassword())) {
            // TODO Verify
            builder.setProxyAuthenticationStrategy(new DefaultAuthenticationStrategy());
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(proxySettings.host(), proxySettings.port()), new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword().toCharArray()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    final SSLContext sslContext = buildSslContext(trustStoreSettings, trustSelfSignedCertificates, trustedHosts);
    LayeredConnectionSocketFactory sslSocketFactory = buildSslConnectionSocketFactory(sslContext);
    PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
    builder.setConnectionManager(connectionManager);
    return builder.build();
}
Also used : SSLContext(javax.net.ssl.SSLContext) AuthScope(org.apache.hc.client5.http.auth.AuthScope) Enumeration(java.util.Enumeration) CharCodingConfig(org.apache.hc.core5.http.config.CharCodingConfig) LayeredConnectionSocketFactory(org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory) Exceptions.throwUnchecked(com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) TextUtils(org.apache.hc.core5.util.TextUtils) ManagedHttpClientConnectionFactory(org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory) PoolingHttpClientConnectionManagerBuilder(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder) LocalNotifier.notifier(com.github.tomakehurst.wiremock.common.LocalNotifier.notifier) org.apache.hc.client5.http.classic.methods(org.apache.hc.client5.http.classic.methods) URI(java.net.URI) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) StringUtils.isEmpty(org.apache.commons.lang3.StringUtils.isEmpty) java.security(java.security) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) TimeValue(org.apache.hc.core5.util.TimeValue) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) UTF_8(java.nio.charset.StandardCharsets.UTF_8) DefaultAuthenticationStrategy(org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy) NoopHostnameVerifier(org.apache.hc.client5.http.ssl.NoopHostnameVerifier) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager) Timeout(org.apache.hc.core5.util.Timeout) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) com.github.tomakehurst.wiremock.http.ssl(com.github.tomakehurst.wiremock.http.ssl) List(java.util.List) HttpHost(org.apache.hc.core5.http.HttpHost) NO_STORE(com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings.NO_STORE) RequestMethod(com.github.tomakehurst.wiremock.http.RequestMethod) KeyStoreSettings(com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) ProxySettings(com.github.tomakehurst.wiremock.common.ProxySettings) Collections(java.util.Collections) NO_PROXY(com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) LayeredConnectionSocketFactory(org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory) HttpHost(org.apache.hc.core5.http.HttpHost) AuthScope(org.apache.hc.client5.http.auth.AuthScope) ManagedHttpClientConnectionFactory(org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) DefaultAuthenticationStrategy(org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy) SSLContext(javax.net.ssl.SSLContext) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager)

Example 9 with BasicCredentialsProvider

use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project commons-vfs by apache.

the class Http5FileProvider method createHttpClientContext.

/**
 * Create an {@link HttpClientContext} object for an http4 file system.
 *
 * @param builder Configuration options builder for http4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @param authData The {@code UserAuthentiationData} object
 * @return an {@link HttpClientContext} object
 */
protected HttpClientContext createHttpClientContext(final Http5FileSystemConfigBuilder builder, final GenericFileName rootName, final FileSystemOptions fileSystemOptions, final UserAuthenticationData authData) {
    final HttpClientContext clientContext = HttpClientContext.create();
    final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    clientContext.setCredentialsProvider(credsProvider);
    final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())));
    final char[] password = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()));
    if (!StringUtils.isEmpty(username)) {
        // set root port
        credsProvider.setCredentials(new AuthScope(rootName.getHostName(), rootName.getPort()), new UsernamePasswordCredentials(username, password));
    }
    final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions);
    if (proxyHost != null) {
        final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
        if (proxyAuth != null) {
            final UserAuthenticationData proxyAuthData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD });
            if (proxyAuthData != null) {
                final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.PASSWORD, null));
                // set proxy host port
                credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), proxyCreds);
            }
            if (builder.isPreemptiveAuth(fileSystemOptions)) {
                final AuthCache authCache = new BasicAuthCache();
                final BasicScheme basicAuth = new BasicScheme();
                authCache.put(proxyHost, basicAuth);
                clientContext.setAuthCache(authCache);
            }
        }
    }
    return clientContext;
}
Also used : UserAuthenticationData(org.apache.commons.vfs2.UserAuthenticationData) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) HttpHost(org.apache.hc.core5.http.HttpHost) UserAuthenticator(org.apache.commons.vfs2.UserAuthenticator) AuthScope(org.apache.hc.client5.http.auth.AuthScope) AuthCache(org.apache.hc.client5.http.auth.AuthCache) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Example 10 with BasicCredentialsProvider

use of org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider in project geo-platform by geosdi.

the class DigestPreemptiveSecurityConnector method bindCredentials.

/**
 * @param targetHost
 * @param targetURI
 * @throws Exception
 */
@Override
protected void bindCredentials(@Nonnull(when = NEVER) HttpHost targetHost, @Nonnull(when = NEVER) URI targetURI) throws Exception {
    super.bindCredentials(targetHost, targetURI);
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(targetHost), this.usernamePasswordCredentials);
    localContext.setCredentialsProvider(credentialsProvider);
}
Also used : BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) AuthScope(org.apache.hc.client5.http.auth.AuthScope)

Aggregations

BasicCredentialsProvider (org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider)16 AuthScope (org.apache.hc.client5.http.auth.AuthScope)13 UsernamePasswordCredentials (org.apache.hc.client5.http.auth.UsernamePasswordCredentials)11 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)8 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)6 HttpHost (org.apache.hc.core5.http.HttpHost)6 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)5 URI (java.net.URI)3 Credentials (org.apache.hc.client5.http.auth.Credentials)3 CredentialsStore (org.apache.hc.client5.http.auth.CredentialsStore)3 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)3 SSLContext (javax.net.ssl.SSLContext)2 ServletException (javax.servlet.ServletException)2 AuthCache (org.apache.hc.client5.http.auth.AuthCache)2 CredentialsProvider (org.apache.hc.client5.http.auth.CredentialsProvider)2 BasicAuthCache (org.apache.hc.client5.http.impl.auth.BasicAuthCache)2 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)2 DefaultConnectionReuseStrategy (org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy)2 URIBuilder (org.apache.hc.core5.net.URIBuilder)2 Exceptions.throwUnchecked (com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked)1