您的位置:首页 > 理论基础 > 计算机网络

HttpClient学习研究---第四章:HTTP authenticationHTTP身份验证

2013-10-05 17:03 471 查看

第四章。HTTP authenticationHTTP身份验证

HttpClient provides full support for authentication schemes defined by the HTTP standard specification as well as a number of widely used non-standard authentication schemes such asHttpClient提供全力支持身份验证方案由HTTP标准规范以及许多广泛使用的非标准的认证方案如
NTLM
and和
SPNEGO
.

4.1.
4.1。User credentials用户凭证

Any process of user authentication requires a set of credentials that can be used to establish user identity.
任何用户身份验证的过程需要一系列的证书,可以用来建立用户标识。In the simplest form user credentials can be just a user name / password pair.在最简单的形式用户凭证可以只是一个用户名/密码对。
UsernamePasswordCredentials
represents
a set of credentials consisting of a security principal and a password in clear text.
表示一组凭证组成的一个安全主要和密码以明文。This implementation is sufficient for standard authentication schemes defined by the HTTP standard specification.这个实现是足够的对于标准HTTP身份验证方案中定义的标准规范。

UsernamePasswordCredentials creds = newUsernamePasswordCredentials("user", "pwd");
System.out.println(creds.getUserPrincipal().getName());
System.out.println(creds.getPassword());

stdout >stdout >

user
pwd

NTCredentials
is a Microsoft Windows specific implementation that includes in addition to the user name / password pair a set of additional Windows specific attributes such as the name of the
user domain. 是微软Windows特定的实现,包含除了用户名/密码对一组额外的Windows特定的属性,如用户域的名称。In a Microsoft Windows network the same user can belong to multiple domains each with a different set of authorizations.在微软Windows网络相同的用户可以属于多个域每一组不同的授权。

NTCredentials creds = new NTCredentials("user", "pwd", "workstation", "domain");
System.out.println(creds.getUserPrincipal().getName());
System.out.println(creds.getPassword());

stdout >stdout >

DOMAIN/user
pwd


4.2.
4.2。Authentication schemes身份验证方案

The这个
AuthScheme
interface represents an abstract challenge-response oriented authentication scheme.
接口代表一个抽象的质询-响应导向的身份验证方案。An authentication scheme is expected to support the following functions:身份验证方案预计将支持以下功能:

Parse and process the challenge sent by the target server in response to request for a protected resource.解析和处理挑战目标服务器发送的响应请求一个受保护的资源。

Provide properties of the processed challenge: the authentication scheme type and its parameters, such the realm this authentication scheme is applicable to, if available提供属性的处理的挑战:身份验证方案类型及其参数,这样的领域这身份验证方案适用于,如果可用

Generate the authorization string for the given set of credentials and the HTTP request in response to the actual authorization challenge.生成授权字符串给定组凭证和HTTP请求响应实际的授权的挑战。

Please note that authentication schemes may be stateful involving a series of challenge-response exchanges.请注意,身份验证方案可能有状态涉及一系列的质询-响应交流。

HttpClient ships with severalHttpClient附带几个
AuthScheme
implementations:实现:

Basic:基本的:Basic authentication scheme as defined in RFC 2617.
基本身份验证方案在RFC 2617中定义的。This authentication scheme is insecure, as the credentials are transmitted in clear text.
这种身份验证方案是不安全的,因为凭证是明文传输的。Despite its insecurity Basic authentication scheme is perfectly adequate if used in combination with the TLS/SSL encryption.尽管它不安全感基本身份验证方案是完全足够如果用于结合TLS / SSL加密。

Digest.消化。Digest authentication scheme as defined in RFC 2617.
摘要式身份验证方案在RFC 2617中定义的。Digest authentication scheme is significantly more secure than Basic and can be a good choice for those applications that do not want the overhead of full transport security through TLS/SSL encryption.摘要式身份验证方案明显更安全比基本和可以是一个不错的选择对于那些不希望应用程序的开销全部运输安全通过TLS
/ SSL加密。

NTLM:NTLM:NTLM is a proprietary authentication scheme developed by Microsoft and optimized for Windows platforms.
是一个专有NTLM身份验证方案由微软开发和优化了Windows平台。NTLM is believed to be more secure thanDigest.NTLM被认为是更安全比消化。

SPNEGO:SPNEGO:
SPNEGO
(S年代imple and几种具体实现和
Pprotected包装
GSSAPI

Negonegotiation Mechanism) is atiation机制)是一个
GSSAPI
"pseudo mechanism" that is used to negotiate one of a number
of possible real mechanisms. “伪机制”,用于谈判的几种可能的真正机制。SPNEGO's most visible use is in Microsoft'sSPNEGO最可见的使用是在微软的
HTTP Negotiate
authentication extension.
身份验证扩展。The negotiable sub-mechanisms includeNTLM and Kerberos supported by Active Directory.
子机制的可转让包括NTLM和Kerberos支持活动目录。At present HttpClient only supports the Kerberos sub-mechanism.目前国内外HttpClient只支持Kerberos。

Kerberos:Kerberos:Kerberos authentication implementation.Kerberos身份验证实现。

4.3.
4.3。Credentials provider凭证提供者

Credentials providers are intended to maintain a set of user credentials and to be able to produce user credentials for a particular authentication scope.
证书提供商旨在维护一组用户凭证和能够产生用户凭证为一个特定的认证范围。Authentication scope consists of a host name, a port number, a realm name and an authentication scheme name.
认证范围由一个主机名、端口号、一个域名和一个身份验证方案的名字。When registering credentials with the credentials provider one can provide a wild card (any host, any port, any realm, any scheme) instead of a concrete attribute value.
当注册凭证与凭证提供者一个可以提供一个通配符(任何主机,任何港口,任何领域,任何计划),而不是一个具体的属性值。The credentials provider is then expected to be able to find the closest match for a particular scope if the direct match cannot be found.凭据提供程序是那么期望能够找到最接近的匹配特定范围如果直接匹配不能发现。

HttpClient can work with any physical representation of a credentials provider that implements theHttpClient可以处理任何物理表示的一个凭据提供程序实现
CredentialsProvider
interface.
接口。The default默认
CredentialsProvider
implementation called实现称为
BasicCredentialsProvider
is
a simple implementation backed by a是一个简单的实现支持吗
java.util.HashMap
.

CredentialsProvider credsProvider = newBasicCredentialsProvider();
credsProvider.setCredentials(
newAuthScope("somehost",AuthScope.ANY_PORT),
newUsernamePasswordCredentials("u1", "p1"));
credsProvider.setCredentials(
newAuthScope("somehost", 8080),
newUsernamePasswordCredentials("u2", "p2"));
credsProvider.setCredentials(
newAuthScope("otherhost", 8080,AuthScope.ANY_REALM, "ntlm"),
newUsernamePasswordCredentials("u3", "p3"));

System.out.println(credsProvider.getCredentials(
newAuthScope("somehost", 80, "realm", "basic")));
System.out.println(credsProvider.getCredentials(
newAuthScope("somehost", 8080, "realm", "basic")));
System.out.println(credsProvider.getCredentials(
newAuthScope("otherhost", 8080, "realm", "basic")));
System.out.println(credsProvider.getCredentials(
newAuthScope("otherhost", 8080, null, "ntlm")));

stdout >stdout >

[principal: u1]
[principal: u2]
null
[principal: u3]


4.4.
4.4。HTTP authentication and execution contextHTTP身份验证和执行上下文

HttpClient relies on theHttpClient依赖于
AuthState
class to keep track of detailed information about the state of the authentication process.
类来跟踪详细信息验证过程的状态。HttpClient creates two instances ofHttpClient创建的两个实例
AuthState
in the course of HTTP request execution: one for target host authentication
and another one for proxy authentication. 在HTTP请求的过程执行:一个用于目标主机认证,另一个用于代理身份验证。In case the target server or the proxy require user authentication the respective如果目标服务器或代理需要用户身份验证各自的
AuthScope
instance
will be populated with the实例将被填充
AuthScope
,
AuthScheme
and和
Crednetials
used during
the authentication process. 认证过程中使用。The这个
AuthState
can be examined in order to find out what kind of authentication was requested, whether a matching可以检查以便找出什么样的认证要求,是否匹配
AuthScheme
implementation was found and whether the credentials provider managed to find user credentials for the given authentication scope.实现被发现和凭证是否提供者成功找到给定的用户凭据的身份验证范围。

In the course of HTTP request execution HttpClient adds the following authentication related objects to the execution context:HTTP请求的过程中执行添加以下身份验证相关HttpClient对象来执行上下文:

Lookup
instance representing the actual authentication scheme registry.
实例代表实际的验证方案注册表。The value of this attribute set in the local context takes precedence over the default one.这个属性的值设置在本地上下文优先于默认的一个。

CredentialsProvider
instance representing the actual credentials provider.
实例代表实际的凭证提供者。The value of this attribute set in the local context takes precedence over the default one.这个属性的值设置在本地上下文优先于默认的一个。

AuthState
instance representing the actual target authentication state.
实例代表实际的目标身份验证状态。The value of this attribute set in the local context takes precedence over the default one.这个属性的值设置在本地上下文优先于默认的一个。

AuthState
instance representing the actual proxy authentication state.
实例代表实际的代理身份验证状态。The value of this attribute set in the local context takes precedence over the default one.这个属性的值设置在本地上下文优先于默认的一个。

AuthCache
instance representing the actual authentication data cache.
实例代表实际的验证数据缓存。The value of this attribute set in the local context takes precedence over the default one.这个属性的值设置在本地上下文优先于默认的一个。

The local当地
HttpContext
object can be used to customize the HTTP authentication context prior to request execution, or to examine its state after the
request has been executed:对象可以用来定制HTTP身份验证上下文请求执行之前,或之后检查其状态在请求执行:

CloseableHttpClient httpclient = <...>

CredentialsProvider credsProvider = <...>
Lookup<AuthSchemeProvider> authRegistry = <...>
AuthCache authCache = <...>

HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthSchemeRegistry(authRegistry);
context.setAuthCache(authCache);
HttpGet httpget = new HttpGet("http://somehost/");
CloseableHttpResponse response1 = httpclient.execute(httpget, context);
<...>

AuthState proxyAuthState = context.getProxyAuthState();
System.out.println("Proxy auth state: " + proxyAuthState.getState());
System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme());
System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials());
AuthState targetAuthState = context.getTargetAuthState();
System.out.println("Target auth state: " + targetAuthState.getState());
System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme());
System.out.println("Target auth credentials: " + targetAuthState.getCredentials());


4.5.
4.5。Caching of authentication data缓存的认证数据

As of version 4.1 HttpClient automatically caches information about hosts it has successfully authenticated with.
自版本4.1 HttpClient自���缓存主机信息经过用它已经成功。Please note that one must use the same execution context to execute logically related requests in order for cached authentication data to propagate from one request to another.
请注意,必须使用相同的执行上下文执行逻辑上相关的请求为缓存的身份验证数据传播从一个请求到另一个。Authentication data will be lost as soon as the execution context goes out of scope.身份验证数据将丢失一旦执行上下文超出范围。

4.6.
4.6。Preemptive authentication先发制人的身份验证

HttpClient does not support preemptive authentication out of the box, because if misused or used incorrectly the preemptive authentication can lead to significant security issues, such as sending user credentials in clear
text to an unauthorized third party. HttpClient不支持先占式认证的盒子,因为如果误用或使用不当的先发制人的认证可以导致严重的安全问题,比如用户凭证以明文发送到一个未经授权的第三方。Therefore, users are expected to evaluate potential benefits of preemptive authentication versus security
risks in the context of their specific application environment.因此,用户将评估的潜在好处先占式认证与安全风险在他们的特定应用程序的上下文环境。

Nonethess one can configure HttpClient to authenticate preemptively by prepopulating the authentication data cache.可配置Nonethess HttpClient验证通过prepopulating先发制人的身份验证数据缓存。

CloseableHttpClient httpclient = <...>

HttpHost targetHost = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = newBasicCredentialsProvider();
credsProvider.setCredentials(
newAuthScope(targetHost.getHostName(), targetHost.getPort()),
newUsernamePasswordCredentials("username", "password"));

// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cacheBasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);

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

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();
}
}


4.7.
4.7。NTLM AuthenticationNTLM认证

As of version 4.1 HttpClient provides full support forNTLMv1,NTLMv2, andNTLM2 Session authentication out of the box.
自版本4.1提供全力支持NTLMv1 HttpClient,NTLMv2,NTLM2会话验证出箱。One can still continue using an external人们仍然可以继续使用一个外部的
NTLM
engine such as引擎如JCIFSJCIFSlibrary
developed by the图书馆开发的Sambasambaproject
as a part of their Windows interoperability suite of programs.项目作为她们的Windows互操作性程序套件。

4.7.1.
4.7.1。NTLM connection persistenceNTLM连接持久性

The这个
NTLM
authentication scheme is significantly more expensive in terms of computational overhead and performance impact than the standard身份验证方案是更昂贵的计算开销和性能方面比标准的影响
Basic
and和
Digest
schemes.
方案。This is likely to be one of the main reasons why Microsoft chose to make这可能是一个主要的原因为什么微软选择了把
NTLM
authentication scheme stateful.
身份验证方案状态。That is, once authenticated, the user identity is associated with that connection for its entire life span.
也就是说,一旦用户通过身份认证,身份是与之相关的连接对其整个生命周期。The stateful nature of有状态的本质
NTLM
connections makes connection persistence more complex, as for the obvious reason persistent连接使连接持久性更复杂的,因为很明显的原因持久
NTLM
connections may not be re-used by users with a different user identity.
连接可能不被重用,用户用一个不同的用户身份。The standard connection managers shipped with HttpClient are fully capable of managing stateful connections.
附带的标准连接经理HttpClient完全有能力管理有状态连接。However, it is critically important that logically related requests within the same session use the same execution context in order to make them aware of the current user identity.
然而,它是非常重要的,逻辑上相关的请求在同一会话中使用相同的执行上下文为了使他们意识到当前用户身份。Otherwise, HttpClient will end up creating a new HTTP connection for each HTTP request against否则,HttpClient最终将创建一个新的HTTP连接每个HTTP请求的反对
NTLM
protected
resources. 受保护的资源。For detailed discussion on stateful HTTP connections please refer to详细的讨论有状态的HTTP连接请参考this这section.部分。

As作为
NTLM
connections are stateful it is generally recommended to trigger连接���态通常建议来触发
NTLM
authentication
using a relatively cheap method, such as身份验证使用相对便宜的方法,如
GET
or或
HEAD
, and re-use the same connection to execute more expensive
methods, especially those enclose a request entity, such as,和重用相同的连接来执行更多的昂贵的方法,尤其是那些附上一个请求的实体,如
POST
or或
PUT
.

CloseableHttpClient httpclient = <...>

CredentialsProvider credsProvider = newBasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("user", "pwd", "myworkstation", "microsoft.com"));

HttpHost target = new HttpHost("www.microsoft.com", 80, "http");

// Make sure the same context is used to execute logically related requests
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);

// Execute a cheap method first. This will triggerNTLM authentication
HttpGet httpget = new HttpGet("/ntlm-protected/info");
CloseableHttpResponse response1 = httpclient.execute(target, httpget, context);
try {
HttpEntity entity1 = response1.getEntity();
} finally {
response1.close();
}

// Execute an expensive method next reusing the same context (and connection)
HttpPost httppost = new HttpPost("/ntlm-protected/form");
httppost.setEntity(new StringEntity("lots and lots of data"));
CloseableHttpResponse response2 = httpclient.execute(target, httppost, context);
try {
HttpEntity entity2 = response2.getEntity();
} finally {
response2.close();
}


4.8.4.8。
SPNEGO
/Kerberos Authentication/ Kerberos身份验证

The这个
SPNEGO
(S年代imple and几种具体实现和
Pprotected包装
GSSAPI

Negonegotiation Mechanism) is designed to allow for authentication to services when neither end knows what the other can use/provide.
tiation机制)被设计成允许身份认证服务结束时既不知道其他可以使用/提供。It is most commonly used to do Kerberos authentication.
它是最常用来做Kerberos身份验证。It can wrap other mechanisms, however the current version in HttpClient is designed solely with Kerberos in mind.它可以用其他机制,然而当前版本在设计使用Kerberos HttpClient完全记住。

Client Web Browser does HTTPGET for resource.客户端Web浏览器并HTTPGET为资源。

Web server returns HTTP 401 status and a header:Web服务器将返回HTTP 401状态和一个标题:
WWW-Authenticate: Negotiate


Client generates a客户机生成一个
NegTokenInit
, base64 encodes it, and resubmits the,base64编码,重新提交
GET
with
anAuthorization header:与一个授权头:
Authorization: Negotiate <base64 encoding>
.

Server decodes the服务器解码
NegTokenInit
, extracts the supported,提取支持
MechTypes
(only Kerberos
V5 in our case), ensures it is one of the expected ones, and then extracts the(在我们的案例中只有Kerberos V5),确保它是预期的事件,然后提取
MechToken
(Kerberos Token) and authenticates it.(Kerberos令牌),并对其进行身份验证。

If more processing is required another HTTP 401 is returned to the client with more data in the the如果需要更多的处理是另一个HTTP 401返回给客户更多的数据
WWW-Authenticate
header.
头。Client takes the info and generates another token passing this back in the客户需要的信息,并生成另一个令牌传递这回到
Authorization
header until complete.头,直到完成。

When the client has been authenticated the Web server should return the HTTP 200 status, a final当客户端验证Web服务器应该返回HTTP 200状态,最后一个
WWW-Authenticate
header and
the page content.标题和页面内容。

4.8.1.4 8 1。
SPNEGO
support in HttpClient支持HttpClient

The这个
SPNEGO
authentication scheme is compatible with Sun Java versions 1.5 and up.
身份验证方案兼容Sun Java版本1.5和起来。However the use of Java >= 1.6 is strongly recommended as it supports然而使用Java > = 1.6是强烈推荐的,因为它支持
SPNEGO
authentication more completely.身份验证更完全。

The Sun JRE provides the supporting classes to do nearly all the Kerberos and太阳JRE提供了支持类做几乎所有的Kerberos和
SPNEGO
token handling.
令牌处理。This means that a lot of the setup is for the GSS classes.
这意味着大量的设置是为GSS类。The这个
SPNegoScheme
is a simple class to handle marshalling the tokens and reading and writing the correct headers.是一个简单的类处理编组的令牌和读写正确的标题。

The best way to start is to grab the最好的开始方式是抓起
KerberosHttpClient.java
file in examples and try and get it to work.
文件的例子,试着让它工作。There are a lot of issues that can happen but if lucky it'll work without too much of a problem.
有很多问题会发生但如果幸运会工作没有太大的问题。It should also provide some output to debug with.它还应该提供一些输出调试用。

In Windows it should default to using the logged in credentials; this can be overridden by using 'kinit' e.g.在Windows中它应该默认为使用登录凭证;这也能被使用的kinit”如。
$JAVA_HOME\bin\kinit testuser@AD.EXAMPLE.NET
,
which is very helpful for testing and debugging issues. ,这是非常有用的对于测试和调试问题。Remove the cache file created by kinit to revert back to the windows Kerberos cache.删除缓存文件由kinit恢复到windows Kerberos缓存。

Make sure to list确保列表
domain_realms
in the在
krb5.conf
file.
文件。This is a major source of problems.这是一个主要的问题。

4.8.2.
4 8 2。GSS/Java Kerberos SetupGSS / Java Kerberos设置

This documentation assumes you are using Windows but much of the information applies to Unix as well.本文档假设您使用的是Windows,但大部分的信息适用于Unix为好。

The这个
org.ietf.jgss
classes have lots of possible configuration parameters, mainly in the类有很多可能的配置参数,主要是在
krb5.conf
/
krb5.ini
file.
文件。Some more info on the format at一些更多的信息的格式http://web.mit.edu/kerberos/krb5-1.4/krb5-1.4.1/doc/krb5-admin/krb5.conf.htmlhttp://web.mit.edu/kerberos/krb5
- 1.4 - / - - - - - - - admin/krb5.conf.html krb5 1.4.1/doc/krb5.

4.8.3.4 8 3。
login.conf
file文件

The following configuration is a basic setup that works in Windows XP against both下面的配置是一个基本的设置,在Windows XP对抗双方的工作
IIS
and和
JBoss
Negotiation
modules.模块。

The system property系统属性
java.security.auth.login.config
can be used to point at the可以用来指向
login.conf
file.文件。

login.conf
content may look like the following:内容可能看起来如下:

com.sun.security.jgss.login {
com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true;
};

com.sun.security.jgss.initiate {
com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true;
};

com.sun.security.jgss.accept {
com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true;
};


4.8.4.4 8 4。
krb5.conf
/
krb5.ini
file文件

If unspecified, the system default will be used.
��果没有指定,默认将使用的系统。Override if needed by setting the system property如果需要覆盖通过设置系统属性
java.security.krb5.conf
to point to a custom指向一个定制
krb5.conf
file.文件。

krb5.conf
content may look like the following:内容可能看起来如下:

[libdefaults]
default_realm = AD.EXAMPLE.NET
udp_preference_limit = 1
[realms]
AD.EXAMPLE.NET = {
kdc = KDC.AD.EXAMPLE.NET
}
[domain_realms]
.ad.example.net=AD.EXAMPLE.NET
ad.example.net=AD.EXAMPLE.NET


4.8.5.
4 8 5。Windows Specific configurationWindows特定的配置

To allow Windows to use the current user's tickets, the system property允许Windows使用当前用户的门票,系统属性
javax.security.auth.useSubjectCredsOnly
must be set to必须设置为
false
and the Windows registry key和Windows的注册表键
allowtgtsessionkey
should be added and set correctly to allow session keys to be sent in the Kerberos Ticket-Granting
Ticket.应该添加和正确设置允许发送会话密钥在Kerberos票据授予票。

On the Windows Server 2003 and Windows 2000 SP4, here is the required registry setting:在Windows Server 2003和Windows 2000 SP4,这里是必需的注册表设置:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
Value Name:allowtgtsessionkey
Value Type: REG_DWORD
Value: 0x01


Here is the location of the registry setting on Windows XP SP2:下面是注册表设置的位置在Windows XP SP2:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\
Value Name:allowtgtsessionkey
Value Type: REG_DWORD
Value: 0x01
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HttpClient
相关文章推荐