微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HttpClientBuilder的基本身份validation

由于HttpClient 4.3,我一直在使用HttpClientBuilder。 我正在连接到具有基本身份validation的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)。 出了什么问题?

通过AJP将REMOTE_USER转发给tomcat(例如shibboleth)

在CentOS 5.7上mod_wsgi禁止错误

Mod-Rewrite REGEX不能正常工作Apache

mod_rewrite在url中使用variables的数字位置

用于访问另一个域上的文件的CORS标头

从这里的抢先认证文档:

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

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

解决方法是使用身份验证缓存来假装您已经连接到服务器一次。 这意味着您只会进行一个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_HOST和AuthScope.ANY_PORT就像你的例子。

实际上,由于您已经信任服务器,所以您最好自己构建授权头。

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

这只是其中的一种情况,阅读规范更容易,并自行推出。

我只是尝试了你的代码示例(对一个简单的基本身份验证启用URL),它工作正常 – 这是来自HttpClient的日志 – 简化一点:

web - 2014-01-04 12:43:19,700 [main] DEBUG oahcprotocol.RequestAddCookies - CookieSpec selected: best-match web - 2014-01-04 12:43:19,710 [main] DEBUG oahcprotocol.RequestAuthCache - Auth cache not set in the context web - 2014-01-04 12:43:19,728 [main] DEBUG oahimpl.execchain.MainClientExec - opening connection {}->http://localhost:8080 web - 2014-01-04 12:43:19,730 [main] DEBUG oahcHttpClientConnectionManager - Connecting to localhost/127.0.0.1:8080 web - 2014-01-04 12:43:19,731 [main] DEBUG oahimpl.execchain.MainClientExec - Executing request GET /spring-security-mvc-basic-auth/homepage.html HTTP/1.1 web - 2014-01-04 12:43:19,731 [main] DEBUG oahimpl.execchain.MainClientExec - Target auth state: UNCHALLENGED web - 2014-01-04 12:43:19,731 [main] DEBUG oahimpl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED web - 2014-01-04 12:43:19,732 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> GET /spring-security-mvc-basic-auth/homepage.html HTTP/1.1 web - 2014-01-04 12:43:19,732 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: localhost:8080 web - 2014-01-04 12:43:19,732 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.3.1 (java 1.5) web - 2014-01-04 12:43:19,735 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 401 Unauthorized web - 2014-01-04 12:43:19,735 [main] DEBUG org.apache.http.headers - http-outgoing-0 << server: Apache-Coyote/1.1 web - 2014-01-04 12:43:19,735 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Set-Cookie: JSESSIONID=B8E6D0D7DE0C99991A74E9B2E4EA68AE; Path=/spring-security-mvc-basic-auth/; HttpOnly web - 2014-01-04 12:43:19,735 [main] DEBUG org.apache.http.headers - http-outgoing-0 << WWW-Authenticate: Basic realm="Baeldung" web - 2014-01-04 12:43:19,735 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Length: 75 web - 2014-01-04 12:43:19,735 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Sat,04 Jan 2014 10:43:19 GMT web - 2014-01-04 12:43:19,738 [main] DEBUG oahttp.impl.auth.HttpAuthenticator - Authentication required web - 2014-01-04 12:43:19,738 [main] DEBUG oahttp.impl.auth.HttpAuthenticator - localhost:8080 requested authentication web - 2014-01-04 12:43:19,738 [main] DEBUG oahicTargetAuthenticationStrategy - Authentication schemes in the order of preference: [negotiate,Kerberos,NTLM,Digest,Basic] web - 2014-01-04 12:43:19,738 [main] DEBUG oahicTargetAuthenticationStrategy - Challenge for negotiate authentication scheme not available web - 2014-01-04 12:43:19,738 [main] DEBUG oahicTargetAuthenticationStrategy - Challenge for Kerberos authentication scheme not available web - 2014-01-04 12:43:19,738 [main] DEBUG oahicTargetAuthenticationStrategy - Challenge for NTLM authentication scheme not available web - 2014-01-04 12:43:19,738 [main] DEBUG oahicTargetAuthenticationStrategy - Challenge for Digest authentication scheme not available web - 2014-01-04 12:43:19,745 [main] DEBUG oahttp.impl.auth.HttpAuthenticator - Selected authentication options: [BASIC] web - 2014-01-04 12:43:19,746 [main] DEBUG oahimpl.execchain.MainClientExec - Executing request GET /spring-security-mvc-basic-auth/homepage.html HTTP/1.1 web - 2014-01-04 12:43:19,746 [main] DEBUG oahimpl.execchain.MainClientExec - Target auth state: CHALLENGED web - 2014-01-04 12:43:19,746 [main] DEBUG oahttp.impl.auth.HttpAuthenticator - Generating response to an authentication challenge using basic scheme web - 2014-01-04 12:43:19,747 [main] DEBUG oahimpl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED web - 2014-01-04 12:43:19,747 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> GET /spring-security-mvc-basic-auth/homepage.html HTTP/1.1 web - 2014-01-04 12:43:19,747 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: localhost:8080 web - 2014-01-04 12:43:19,747 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.3.1 (java 1.5) web - 2014-01-04 12:43:19,747 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Authorization: Basic dXNlcjE6dXNlcjFQYXNz web - 2014-01-04 12:43:19,750 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 200 OK web - 2014-01-04 12:43:19,750 [main] DEBUG org.apache.http.headers - http-outgoing-0 << server: Apache-Coyote/1.1 web - 2014-01-04 12:43:19,750 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Set-Cookie: JSESSIONID=C03FD4EB1421A4C3A003ADC895D49599; Path=/spring-security-mvc-basic-auth/; HttpOnly web - 2014-01-04 12:43:19,750 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: text/html;charset=ISO-8859-1 web - 2014-01-04 12:43:19,750 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Language: en-US web - 2014-01-04 12:43:19,751 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Length: 96 web - 2014-01-04 12:43:19,751 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Sat,751 [main] DEBUG oahttp.impl.auth.HttpAuthenticator - Authentication succeeded web - 2014-01-04 12:43:19,751 [main] DEBUG oahicTargetAuthenticationStrategy - Caching 'basic' auth scheme for http://localhost:8080 web - 2014-01-04 12:43:19,760 [main] DEBUG oahcpResponseProcessCookies - Cookie accepted: "[version: 0][name: JSESSIONID][value: C03FD4EB1421A4C3A003ADC895D49599][domain: localhost][path: /spring-security-mvc-basic-auth/][expiry: null]".

所以 – 简单地说:

– 服务器确实挑战最初的请求

– HttpClient识别基本认证方案并正确回应挑战

在这一点上,服务器服务器的预期200 OK

可能是您使用的REST服务实际上并未使用基本身份验证。 您可以尝试粘贴完整的HttpClient日志以更好地诊断问题。

希望有所帮助。

我认为 HttpClient就像其他基于curl的解决方案,它遵循规范。

规范是“不要发送证书,除非服务器告诉你这样做”。 所以你得到一个401(“我想你发送凭据”)…

这是一个常见的肥皂用户问题:当你不知道的时候,这个问题并不明显

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐