Search in sources :

Example 36 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project camel by apache.

the class ProxyHttpClientConfigurer method configureHttpClient.

public void configureHttpClient(HttpClientBuilder clientBuilder) {
    clientBuilder.setProxy(new HttpHost(host, port, scheme));
    if (username != null && password != null) {
        Credentials defaultcreds;
        if (domain != null) {
            defaultcreds = new NTCredentials(username, password, ntHost, domain);
        } else {
            defaultcreds = new UsernamePasswordCredentials(username, password);
        }
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, defaultcreds);
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NTCredentials(org.apache.http.auth.NTCredentials) Credentials(org.apache.http.auth.Credentials) NTCredentials(org.apache.http.auth.NTCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 37 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project camel by apache.

the class BasicAuthenticationHttpClientConfigurer method configureHttpClient.

public void configureHttpClient(HttpClientBuilder clientBuilder) {
    Credentials defaultcreds;
    if (domain != null) {
        defaultcreds = new NTCredentials(username, password, host, domain);
    } else {
        defaultcreds = new UsernamePasswordCredentials(username, password);
    }
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, defaultcreds);
    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NTCredentials(org.apache.http.auth.NTCredentials) Credentials(org.apache.http.auth.Credentials) NTCredentials(org.apache.http.auth.NTCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 38 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project elasticsearch by elastic.

the class RestClientSingleHostIntegTests method createRestClient.

private static RestClient createRestClient(final boolean useAuth, final boolean usePreemptiveAuth) {
    // provide the username/password for every request
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "pass"));
    final RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort())).setDefaultHeaders(defaultHeaders);
    if (pathPrefix.length() > 0) {
        // sometimes cut off the leading slash
        restClientBuilder.setPathPrefix(randomBoolean() ? pathPrefix.substring(1) : pathPrefix);
    }
    if (useAuth) {
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

            @Override
            public HttpAsyncClientBuilder customizeHttpClient(final HttpAsyncClientBuilder httpClientBuilder) {
                if (usePreemptiveAuth == false) {
                    // disable preemptive auth by ignoring any authcache
                    httpClientBuilder.disableAuthCaching();
                }
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
    }
    return restClientBuilder.build();
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder)

Example 39 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project dropwizard by dropwizard.

the class HttpClientBuilder method createClient.

/**
     * Map the parameters in {@link HttpClientConfiguration} to configuration on a
     * {@link org.apache.http.impl.client.HttpClientBuilder} instance
     *
     * @param builder
     * @param manager
     * @param name
     * @return the configured {@link CloseableHttpClient}
     */
protected ConfiguredCloseableHttpClient createClient(final org.apache.http.impl.client.HttpClientBuilder builder, final InstrumentedHttpClientConnectionManager manager, final String name) {
    final String cookiePolicy = configuration.isCookiesEnabled() ? CookieSpecs.DEFAULT : CookieSpecs.IGNORE_COOKIES;
    final Integer timeout = (int) configuration.getTimeout().toMilliseconds();
    final Integer connectionTimeout = (int) configuration.getConnectionTimeout().toMilliseconds();
    final Integer connectionRequestTimeout = (int) configuration.getConnectionRequestTimeout().toMilliseconds();
    final long keepAlive = configuration.getKeepAlive().toMilliseconds();
    final ConnectionReuseStrategy reuseStrategy = keepAlive == 0 ? new NoConnectionReuseStrategy() : new DefaultConnectionReuseStrategy();
    final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0 ? NO_RETRIES : (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(), false) : httpRequestRetryHandler);
    final RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(cookiePolicy).setSocketTimeout(timeout).setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
    final SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build();
    customizeBuilder(builder).setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, name)).setConnectionManager(manager).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig).setConnectionReuseStrategy(reuseStrategy).setRetryHandler(retryHandler).setUserAgent(createUserAgent(name));
    if (keepAlive != 0) {
        // either keep alive based on response header Keep-Alive,
        // or if the server can keep a persistent connection (-1), then override based on client's configuration
        builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {

            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                final long duration = super.getKeepAliveDuration(response, context);
                return (duration == -1) ? keepAlive : duration;
            }
        });
    }
    // create a tunnel through a proxy host if it's specified in the config
    final ProxyConfiguration proxy = configuration.getProxyConfiguration();
    if (proxy != null) {
        final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
        builder.setRoutePlanner(new NonProxyListProxyRoutePlanner(httpHost, proxy.getNonProxyHosts()));
        // if the proxy host requires authentication then add the host credentials to the credentials provider
        final AuthConfiguration auth = proxy.getAuth();
        if (auth != null) {
            if (credentialsProvider == null) {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }
    }
    if (credentialsProvider != null) {
        builder.setDefaultCredentialsProvider(credentialsProvider);
    }
    if (routePlanner != null) {
        builder.setRoutePlanner(routePlanner);
    }
    if (disableContentCompression) {
        builder.disableContentCompression();
    }
    if (redirectStrategy != null) {
        builder.setRedirectStrategy(redirectStrategy);
    }
    if (defaultHeaders != null) {
        builder.setDefaultHeaders(defaultHeaders);
    }
    if (verifier != null) {
        builder.setSSLHostnameVerifier(verifier);
    }
    if (httpProcessor != null) {
        builder.setHttpProcessor(httpProcessor);
    }
    return new ConfiguredCloseableHttpClient(builder.build(), requestConfig);
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) NonProxyListProxyRoutePlanner(io.dropwizard.client.proxy.NonProxyListProxyRoutePlanner) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) AuthConfiguration(io.dropwizard.client.proxy.AuthConfiguration) InstrumentedHttpRequestExecutor(com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) ProxyConfiguration(io.dropwizard.client.proxy.ProxyConfiguration) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) ConnectionReuseStrategy(org.apache.http.ConnectionReuseStrategy) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler)

Example 40 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project elasticsearch by elastic.

the class TransportReindexAction method buildRestClient.

/**
     * Build the {@link RestClient} used for reindexing from remote clusters.
     * @param remoteInfo connection information for the remote cluster
     * @param taskId the id of the current task. This is added to the thread name for easier tracking
     * @param threadCollector a list in which we collect all the threads created by the client
     */
static RestClient buildRestClient(RemoteInfo remoteInfo, long taskId, List<Thread> threadCollector) {
    Header[] clientHeaders = new Header[remoteInfo.getHeaders().size()];
    int i = 0;
    for (Map.Entry<String, String> header : remoteInfo.getHeaders().entrySet()) {
        clientHeaders[i] = new BasicHeader(header.getKey(), header.getValue());
    }
    return RestClient.builder(new HttpHost(remoteInfo.getHost(), remoteInfo.getPort(), remoteInfo.getScheme())).setDefaultHeaders(clientHeaders).setRequestConfigCallback(c -> {
        c.setConnectTimeout(Math.toIntExact(remoteInfo.getConnectTimeout().millis()));
        c.setSocketTimeout(Math.toIntExact(remoteInfo.getSocketTimeout().millis()));
        return c;
    }).setHttpClientConfigCallback(c -> {
        if (remoteInfo.getUsername() != null) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(remoteInfo.getUsername(), remoteInfo.getPassword());
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, creds);
            c.setDefaultCredentialsProvider(credentialsProvider);
        }
        AtomicInteger threads = new AtomicInteger();
        c.setThreadFactory(r -> {
            String name = "es-client-" + taskId + "-" + threads.getAndIncrement();
            Thread t = new Thread(r, name);
            threadCollector.add(t);
            return t;
        });
        c.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());
        return c;
    }).build();
}
Also used : Versions(org.elasticsearch.common.lucene.uid.Versions) RemoteScrollableHitSource(org.elasticsearch.index.reindex.remote.RemoteScrollableHitSource) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) Property(org.elasticsearch.common.settings.Setting.Property) BiFunction(java.util.function.BiFunction) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Header(org.apache.http.Header) VersionType(org.elasticsearch.index.VersionType) AutoCreateIndex(org.elasticsearch.action.support.AutoCreateIndex) RemoteInfo(org.elasticsearch.index.reindex.remote.RemoteInfo) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) IndexRequest(org.elasticsearch.action.index.IndexRequest) ClusterState(org.elasticsearch.cluster.ClusterState) Operations(org.apache.lucene.util.automaton.Operations) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ParentBulkByScrollTask(org.elasticsearch.action.bulk.byscroll.ParentBulkByScrollTask) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Failure(org.elasticsearch.action.bulk.BulkItemResponse.Failure) Automata(org.apache.lucene.util.automaton.Automata) AbstractAsyncBulkByScrollAction(org.elasticsearch.action.bulk.byscroll.AbstractAsyncBulkByScrollAction) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) WorkingBulkByScrollTask(org.elasticsearch.action.bulk.byscroll.WorkingBulkByScrollTask) BulkByScrollResponse(org.elasticsearch.action.bulk.byscroll.BulkByScrollResponse) ActionFilters(org.elasticsearch.action.support.ActionFilters) Setting(org.elasticsearch.common.settings.Setting) Collections.synchronizedList(java.util.Collections.synchronizedList) Automaton(org.apache.lucene.util.automaton.Automaton) Collections.emptyList(java.util.Collections.emptyList) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) CredentialsProvider(org.apache.http.client.CredentialsProvider) Task(org.elasticsearch.tasks.Task) RestClient(org.elasticsearch.client.RestClient) XContentType(org.elasticsearch.common.xcontent.XContentType) ClusterService(org.elasticsearch.cluster.service.ClusterService) SearchRequest(org.elasticsearch.action.search.SearchRequest) INTERNAL(org.elasticsearch.index.VersionType.INTERNAL) Function(java.util.function.Function) BackoffPolicy(org.elasticsearch.action.bulk.BackoffPolicy) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ScrollableHitSource(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource) HandledTransportAction(org.elasticsearch.action.support.HandledTransportAction) ParentTaskAssigningClient(org.elasticsearch.client.ParentTaskAssigningClient) Objects.requireNonNull(java.util.Objects.requireNonNull) Regex(org.elasticsearch.common.regex.Regex) TransportService(org.elasticsearch.transport.TransportService) CharacterRunAutomaton(org.apache.lucene.util.automaton.CharacterRunAutomaton) Script(org.elasticsearch.script.Script) BulkByScrollParallelizationHelper(org.elasticsearch.action.bulk.byscroll.BulkByScrollParallelizationHelper) Client(org.elasticsearch.client.Client) IOException(java.io.IOException) MinimizationOperations(org.apache.lucene.util.automaton.MinimizationOperations) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) XContentParser(org.elasticsearch.common.xcontent.XContentParser) VersionFieldMapper(org.elasticsearch.index.mapper.VersionFieldMapper) AuthScope(org.apache.http.auth.AuthScope) SearchFailure(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.SearchFailure) BasicHeader(org.apache.http.message.BasicHeader) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) HttpHost(org.apache.http.HttpHost) ScriptService(org.elasticsearch.script.ScriptService) ActionListener(org.elasticsearch.action.ActionListener) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpHost(org.apache.http.HttpHost) Map(java.util.Map) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)85 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)70 CredentialsProvider (org.apache.http.client.CredentialsProvider)58 AuthScope (org.apache.http.auth.AuthScope)46 HttpHost (org.apache.http.HttpHost)24 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)21 HttpGet (org.apache.http.client.methods.HttpGet)19 HttpResponse (org.apache.http.HttpResponse)17 HttpClient (org.apache.http.client.HttpClient)15 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)15 IOException (java.io.IOException)14 AuthCache (org.apache.http.client.AuthCache)12 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)12 BasicScheme (org.apache.http.impl.auth.BasicScheme)11 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)11 RequestConfig (org.apache.http.client.config.RequestConfig)9 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)9 Test (org.junit.Test)8 HttpEntity (org.apache.http.HttpEntity)6 AuthSchemeProvider (org.apache.http.auth.AuthSchemeProvider)6