HttpClientBuilder基本身份验证 [英] HttpClientBuilder basic auth

查看:674
本文介绍了HttpClientBuilder基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于HttpClient的4.3,我一直使用HttpClientBuilder。我连接至​​具有基本身份验证的REST服务。我设置的凭据如下:

Since HttpClient 4.3, I have been using the HttpClientBuilder. I am connecting to a REST service that has basic authentication. I am setting the credentials as follows:

HttpClientBuilder builder = HttpClientBuilder.create();

// Get the client credentials
String username = Config.get(Constants.CONFIG_USERNAME);
String password = Config.get(Constants.CONFIG_PASSWORD);

// If username and password was found, inject the credentials
if (username != null && password != null)
{
    CredentialsProvider provider = new BasicCredentialsProvider();

    // Create the authentication scope
    AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

    // Create credential pair
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    // Inject the credentials
    provider.setCredentials(scope, credentials);

    // Set the default credentials provider
    builder.setDefaultCredentialsProvider(provider);
}

但是,这并不工作(我使用REST服务将返回401)。这是怎么回事了?

However, this does not work (the REST service that I am using is returning 401). What is going wrong?

推荐答案

preemptive认证文件位置:

<一个href=\"http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html\">http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

在默认情况下,HttpClient的将不pemptively提供凭据$ P $,它会首先创建一个没有认证参数的HTTP请求。这是由设计,作为安全性precaution,并作为规范的一部分。但是,这会导致问题,如果你不重试连接,或任何你要连接到希望你的第一个连接上发送验证信息。这也导致额外的等待时间的请求,因为你需要多次调用,并导致401S出现在日志中。

By default, httpclient will not provide credentials preemptively, it will first create a HTTP request without authentication parameters. This is by design, as a security precaution, and as part of the spec. But, this causes issues if you don't retry the connection, or wherever you're connecting to expects you to send authentication details on the first connection. It also causes extra latency to a request, as you need to make multiple calls, and causes 401s to appear in the logs.

解决方法是使用身份验证缓存来,你已经连接到服务器一旦pretend。这意味着你将只能做一个HTTP调用,并在日志中不会看到401:

The workaround is to use an authentication cache to pretend that you've already connected to the server once. This means you'll only make one HTTP call and won't see a 401 in the logs:

CloseableHttpClient httpclient = HttpClientBuilder.create().build();

HttpHost targetHost = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
        new UsernamePasswordCredentials("username", "password"));

// 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(targetHost, basicAuth);

// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);

HttpGet httpget = new HttpGet("/");
for (int i = 0; i < 3; i++) {
    CloseableHttpResponse response = httpclient.execute(
            targetHost, httpget, context);
    try {
        HttpEntity entity = response.getEntity();

    } finally {
        response.close();
    }
}

请注意:你必须相信你连接到主机,如果您正在使用HTTP,您的用户名和密码以明文发送(当然,基数64,但不计)。

Please note: You need to trust the host you're connecting to, and if you're using HTTP, your username and password will be sent in cleartext (well, base64, but that doesn't count).

您也应该使用更具体的Authscope而不是依靠 AuthScope .ANY_HOST AuthScope.ANY_PORT 喜欢在你的榜样。

You should also be using a much more specific Authscope rather than relying on AuthScope .ANY_HOST and AuthScope.ANY_PORT like in your example.

这篇关于HttpClientBuilder基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆