Search in sources :

Example 6 with AuthScope

use of org.apache.hc.client5.http.auth.AuthScope 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 AuthScope

use of org.apache.hc.client5.http.auth.AuthScope 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 AuthScope

use of org.apache.hc.client5.http.auth.AuthScope 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 AuthScope

use of org.apache.hc.client5.http.auth.AuthScope 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 AuthScope

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

the class AbstractSecurityConnector method bindCredentials.

/**
 * Bind Credentials for {@link CredentialsStore} class
 *
 * @param credentialsStore
 * @param targetURI
 */
protected void bindCredentials(@Nonnull(when = NEVER) CredentialsStore credentialsStore, @Nonnull(when = NEVER) URI targetURI) {
    checkArgument(credentialsStore != null, "The Parameter credentialsProvider must not be null.");
    checkArgument(targetURI != null, "The Parameter targetURI must not be null.");
    if (this.authScope == null) {
        this.authScope = new AuthScope(targetURI.getHost(), targetURI.getPort());
    }
    credentialsStore.setCredentials(authScope, this.usernamePasswordCredentials);
}
Also used : AuthScope(org.apache.hc.client5.http.auth.AuthScope)

Aggregations

AuthScope (org.apache.hc.client5.http.auth.AuthScope)16 UsernamePasswordCredentials (org.apache.hc.client5.http.auth.UsernamePasswordCredentials)14 BasicCredentialsProvider (org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider)13 Credentials (org.apache.hc.client5.http.auth.Credentials)6 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)5 HttpHost (org.apache.hc.core5.http.HttpHost)5 CredentialsStore (org.apache.hc.client5.http.auth.CredentialsStore)3 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)3 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)3 AuthCache (org.apache.hc.client5.http.auth.AuthCache)2 NTCredentials (org.apache.hc.client5.http.auth.NTCredentials)2 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)2 BasicAuthCache (org.apache.hc.client5.http.impl.auth.BasicAuthCache)2 Exceptions.throwUnchecked (com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked)1 LocalNotifier.notifier (com.github.tomakehurst.wiremock.common.LocalNotifier.notifier)1 ProxySettings (com.github.tomakehurst.wiremock.common.ProxySettings)1 NO_PROXY (com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY)1 KeyStoreSettings (com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings)1 NO_STORE (com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings.NO_STORE)1 RequestMethod (com.github.tomakehurst.wiremock.http.RequestMethod)1