Introduction
HttpClient supports three different types of http authentication schemes: Basic, Digest and NTLM. These can be used to authenticate with http servers or proxies.
Server Authentication
HttpClient handles authenticating with servers almost transparently, the only thing a developer must do is actually provide the login credentials. These credentials are stored in the HttpState instance and can be set or retrieved using the setCredentials(AuthScope authscope, Credentials cred)
and getCredentials(AuthScope authscope)
methods.
The automatic authorization built in to HttpClient can be disabled with the method setDoAuthentication(boolean doAuthentication)
in the HttpMethod class. The change only affects that method instance.
Preemptive Authentication
Preemptive authentication can be enabled within HttpClient. In this mode HttpClient will send the basic authentication response even before the server gives an unauthorized response in certain situations, thus reducing the overhead of making the connection. To enable this use the following:
client.getParams().setAuthenticationPreemptive(true);
Preemptive authentication mode also requires default Credentials to be set for the target or proxy host against which preemptive authentication is to be attempted. Failure to provide default credentials will render the preemptive authentication mode ineffective.
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(new AuthScope("myhost", 80, AuthScope.ANY_REALM), defaultcreds);
The preemptive authentication in HttpClient conforms to rfc2617:
A client SHOULD assume that all paths at or deeper than the depth of the last symbolic element in the path field of the Request-URI also are within the protection space specified by the Basic realm value of the current challenge. A client MAY preemptively send the corresponding Authorization header with requests for resources in that space without receipt of another challenge from the server. Similarly, when a client sends a request to a proxy, it may reuse a userid and password in the Proxy-Authorization header field without receiving another challenge from the proxy server.
Security aspects of server authentication
Use default credentials with caution when developing applications that may need to communicate with untrusted web sites or web applications. When preemptive authentication is activated or credentials are not explicitly given for a specific authentication realm and host HttpClient will use default credentials to try to authenticate with the target site. If you want to avoid sending sensitive credentials to an untrusted site, narrow the credentials scope as much as possible: always specify the host and, when known, the realm the credentials are intended for.
Setting credentials with AuthScope.ANY authentication scope (null
value for host and/or realm) is highly discouraged in production applications. Doing this will result in the credentials being sent for all authentication attempts (all requests in the case of preemptive authentication). Use of this setting should be limited to debugging only.
// To be avoided unless in debug mode
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
Proxy Authentication
Proxy authentication in HttpClient is almost identical to server authentication with the exception that the credentials for each are stored independantly. So for proxy authentication you must use setProxyCredentials(AuthScope authscope, Credentials cred)
and getProxyCredentials(AuthScope authscope)
.
Authentication Schemes
The following authentication schemes are supported by HttpClient.
Basic
Basic authentication is the original and most compatible authentication scheme for HTTP. Unfortunately, it is also the least secure as it sends the username and password unencrypted to the server. Basic authentication requires an instance of UsernamePasswordCredentials (which NTCredentials extends) to be available, either for the specific realm specified by the server or as the default credentials.
Digest
Digest authentication was added in the HTTP 1.1 protocol and while not being as widely supported as Basic authentication there is a great deal of support for it. Digest authentication is significantly more secure than basic authentication as it never transfers the actual password across the network, but instead uses it to encrypt a "nonce" value sent from the server.
Digest authentication requires an instance of UsernamePasswordCredentials (which NTCredentials extends) to be available either for the specific realm specified by the server or as the default credentials.
NTLM
NTLM is the most complex of the authentication protocols supported by HttpClient. It is a proprietary protocol designed by Microsoft with no publicly available specification. Early version of NTLM were less secure than Digest authentication due to faults in the design, however these were fixed in a service pack for Windows NT 4 and the protocol is now considered more secure than Digest authentication.
NTLM authentication requires an instance of NTCredentials be available for the domain name of the server or the default credentials. Note that since NTLM does not use the notion of realms HttpClient uses the domain name of the server as the name of the realm. Also note that the username provided to the NTCredentials should not be prefixed with the domain - ie: "adrian" is correct whereas "DOMAIN\adrian" is not correct.
There are some significant differences in the way that NTLM works compared with basic and digest authentication. These differences are generally handled by HttpClient, however having an understanding of these differences can help avoid problems when using NTLM authentication.
- NTLM authentication works almost exactly the same as any other form of authentication in terms of the HttpClient API. The only difference is that you need to supply 'NTCredentials' instead of 'UsernamePasswordCredentials' (NTCredentials actually extends UsernamePasswordCredentials so you can use NTCredentials right throughout your application if need be).
- The realm for NTLM authentication is the domain name of the computer being connected to, this can be troublesome as servers often have multiple domain names that refer to them. Only the domain name that HttpClient connects to (as specified by the HostConfiguration) is used to look up the credentials. It is generally advised that while initially testing NTLM authentication, you pass the realm in as null which is used as the default.
- NTLM authenticates a connection and not a request, so you need to authenticate every time a new connection is made and keeping the connection open during authentication is vital. Due to this, NTLM cannot be used to authenticate with both a proxy and the server, nor can NTLM be used with HTTP 1.0 connections or servers that do not support HTTP keep-alives.
For a detailed explanation of how NTLM authentication works, please see http://davenport.sourceforge.net/ntlm.html.
Alternate authentication
Some servers support multiple schemes for authenticating users. Given that only one scheme may be used at a time for authenticating, HttpClient must choose which scheme to use. To accompish this, HttpClient uses an order of preference to select the correct authentication scheme. By default this order is: NTLM, Digest, Basic.
In certain cases it may be desirable to change this default. The default preference of the authentication schemes may be altered using the 'http.auth.scheme-priority' parameter. The parameter value is expected to be a List of Strings containing names of authentication schemes in descending order of preference.
HttpClient client = new HttpClient();
List authPrefs = new ArrayList(2);
authPrefs.add(AuthPolicy.DIGEST);
authPrefs.add(AuthPolicy.BASIC);
// This will exclude the NTLM authentication scheme
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
Custom authentication scheme
HttpClient natively supports basic, digest, and NTLM authentication. It also contains a mechanism to plugin additional custom authentication schemes via the AuthScheme interface. The following steps are required to make use of a custom authentication scheme.
- Implement the
AuthScheme
interface.
- Register the custom
AuthScheme
with AuthPolicy.registerAuthScheme().
- Include the custom
AuthScheme
in the AuthPolicy.AUTH_SCHEME_PRIORITY preference (see the Alternate authentication section).
Examples
There are a number of authentication examples in the example directory, including:
Known limitations and problems
-
Authentication schemes that rely on persistent connection state do not work on Sun's JVMs below 1.4 if SSL is used
For details please refer to the Known limitations and problems section of the SSL Guide
Workaround: Disable stale connection check or upgrade to Java 1.4 or above.
-
Cannot authenticate with Microsoft IIS using NTLM authentication scheme
NT Lan Manager (NTLM) authentication is a proprietary, closed challenge/response authentication protocol for Microsoft Windows. Only some details about NTLM protocol are available through reverse engineering. HttpClient provides limited support for what is known as NTLMv1, the early version of the NTLM protocol. HttpClient does not support NTLMv2 at all.
Workaround: Disable NTLMv2. For details refer to this Microsoft Support Article
Troubleshooting
Some authentication schemes may use cryptographic algorithms. It is recommended to include the Java Cryptography Extension in your runtime environment prior to JDK 1.4. Also note that you must register the JCE implementation manually as HttpClient will not do so automatically. For instance to register the Sun JCE implementation, you should execute the following code before attempting to use HttpClient.
String secProviderName = "com.sun.crypto.provider.SunJCE");
java.security.Provider secProvider =
(java.security.Provider)Class.forName(secProviderName).newInstance();
Security.addProvider(secProvider);
相关推荐
在使用HttpClient时,开发者需要注意配置连接管理器、设置合适的超时、处理重定向和重试、以及选择合适的认证方式。同时,由于HttpClient的灵活性,正确地关闭和管理连接资源也非常重要,以避免资源泄露。 总之,...
4. **请求令牌(Token Request)**:使用HttpClient,构造一个POST请求到授权服务器的令牌端点,例如`https://auth-server/oauth2/token`。请求体应包含授权码、redirect_uri(如果适用)、grant_type(通常是...
HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod("http://example.com"); int statusCode = httpClient.executeMethod(getMethod); if (statusCode == 200) { System.out....
6. **认证和授权**:HttpClient支持多种身份验证机制,如Basic、Digest、NTLM等,通过`CredentialsProvider`和`AuthSchemeRegistry`来配置。 7. **Cookie管理**:`CookieSpecRegistry`和`CookieStore`接口用于处理...
Commons Logging提供了一种方式来插入不同的日志框架,如Log4j或Java内置的日志系统,这样可以根据项目需求灵活选择日志实现。 3. **commons-codec-1.3.jar**:此库提供了各种编码和解码算法,例如Base64编码、URL...
5. **认证和授权**:HttpClient支持多种认证机制,如Basic、Digest、NTLM和Kerberos,可以处理HTTP基本认证、摘要认证以及Windows域认证。 6. **重定向处理**:HttpClient自动处理HTTP状态码3xx的重定向,但允许...
3. **身份验证**:HttpClient提供了多种认证机制,如Basic、Digest、NTLM等,可以处理复杂的授权需求。 4. **异步请求**:利用Future和Callback,HttpClient支持非阻塞的异步请求,提升系统并发能力。 5. **HTTPS...
七、身份验证和授权 HttpClient支持多种认证机制,包括基本认证、摘要认证、NTLM和Kerberos。通过`CredentialsProvider`和`Authenticator`,可以轻松设置认证信息。 八、Cookie处理 HttpClient 4.5支持标准的...
通过httpclient post去获取,response返回码是302,返回的code放在header的Location中。 请求的时候client_id,response_type,redirect_uri,state拼接在url后面,account和password放在body表单(x-...
4. **认证和授权**:HttpClient支持多种认证机制,包括基本认证、摘要认证、NTLM和Kerberos等。`CredentialsProvider`和`Authenticator`接口用于配置和处理认证过程。 5. **重试和重定向策略**:HttpClient允许用户...
文件列表中的`LICENSE.txt`、`NOTICE.txt`、`README.txt`和`RELEASE_NOTES.txt`分别包含了Apache HttpClient的授权协议信息、版权声明、项目简介和版本发布说明。这些文件对理解项目的许可条件、使用限制和最新更新...
4. **认证和授权**: HttpClient支持多种认证机制,如基本认证、摘要认证、NTLM和Kerberos。你可以通过`CredentialsProvider`和`Authenticator`来配置这些认证策略。 5. **重定向处理**: HttpClient可以自动处理HTTP...
因为微信API通常需要发送POST请求,并可能涉及OAuth2.0授权、JSON数据格式的处理。 6. **连接管理**: - HttpClient提供了连接池管理器(PoolingHttpClientConnectionManager),可以控制连接的创建、复用和关闭,...
7. **身份验证和授权**:HttpClient支持多种身份验证机制,包括基本认证、摘要认证、NTLM和Kerberos等,满足企业级应用的需求。 二、HttpClient 4.5的使用 在Java项目中,引入HttpClient 4.5的jar包至关重要。这些...
4. **认证和授权**:处理基本认证、OAuth、JWT等身份验证机制。 5. **链式调用**:通过链式调用来设置请求属性,提高代码可读性。 在多个系统间进行数据交换时,HttpClient的灵活性和强大功能使其成为理想的工具。...
7. **认证和授权**: `HttpClient`支持多种认证机制,包括基本认证、摘要认证、NTLM和Kerberos。你可以使用`Credentials`接口和`AuthScope`对象来指定认证信息。 8. **Cookie管理**: `CookiePolicy`枚举定义了...
快速API章节主要介绍了一个易于使用的facade API,它提供了简化HTTP请求响应处理的方式。 第六章 HTTP缓存 HTTP缓存是为了提高应用性能和减少服务器负载而引入的。本章内容包括基本概念、与RFC-2616标准的兼容性、...
但是考虑到一些服务授权的问题,很多公司提供的页面往往并不是可以通过一个简单的URL就可以访问的,而必须经过注册然后登录后方可使用提供服务的页面,这个时候就涉及到COOKIE问题的处理。我们知道目前流行的***页...
对于网络请求,`ACCESS_FINE_LOCATION`和`INTERNET`权限成为运行时权限,需要在运行时由用户动态授权。因此,即使在AndroidManifest.xml中声明了`<uses-permission>`,也需要在代码中检查并请求这些权限。 三、...
HTTPClient是一个广泛使用的Java库,它为开发人员提供了一种高效、强大的方式来执行HTTP请求。这个zip文件包含了几个关键的jar包,分别是httpcore、httpclient和可能的其他相关组件,如common,这些组件是构建基于...