HttpClientBuilder basic auth

从HttpClient 4.3开始,我一直在使用HttpClientBuilder。我正在连接到具有基本身份验证的 REST 服务。我按如下方式设置凭据:

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)。哪里出错了?


答案 1

从此处的抢占式身份验证文档:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

默认情况下,httpclient 不会抢先提供凭据,它将首先创建一个没有身份验证参数的 HTTP 请求。这是设计使然,作为安全预防措施,并作为规范的一部分。但是,如果您不重试连接,或者您正在连接的任何位置都希望您在第一个连接上发送身份验证详细信息,则这会导致问题。它还会导致请求出现额外的延迟,因为您需要进行多次调用,并导致 401 出现在日志中。

解决方法是使用身份验证缓存来假装您已经连接到服务器一次。这意味着您只会进行一次 HTTP 调用,并且不会在日志中看到 401:

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,则您的用户名和密码将以明文形式发送(好吧,base64,但这不算在内)。

您还应该使用更具体的Authscope,而不是依赖和喜欢您的示例。AuthScope .ANY_HOSTAuthScope.ANY_PORT


答案 2

实际上,由于您已经信任服务器,因此自己构建授权标头可能是最简单的。

 byte[] credentials = Base64.encodeBase64((username + ":" + password).getBytes(StandardCharsets.UTF_8));
 request.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
 httpClient.execute(request);

这只是其中一种情况,它更容易阅读规范,并自己滚动。


推荐