HttpClient(4.3.5) - HTTP Authentication
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 as NTLM and SPNEGO.
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.
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "pwd");
System.out.println(creds.getUserPrincipal().getName());
System.out.println(creds.getPassword());
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. In a Microsoft Windows network the same user can belong to multiple domains each with a different set of authorizations.
NTCredentials creds = new NTCredentials("user", "pwd", "workstation", "domain");
System.out.println(creds.getUserPrincipal().getName());
System.out.println(creds.getPassword());
stdout >
DOMAIN/user
pwd
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.
Please note that authentication schemes may be stateful involving a series of challenge-response exchanges.
HttpClient ships with several AuthScheme implementations:
- Basic: Basic authentication scheme as defined in 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.
- Digest: Digest authentication scheme as defined in 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.
- NTLM: NTLM is a proprietary authentication scheme developed by Microsoft and optimized for Windows platforms. NTLM is believed to be more secure than Digest.
- SPNEGO: SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) is a GSSAPI "pseudo mechanism" that is used to negotiate one of a number of possible real mechanisms. SPNEGO's most visible use is in Microsoft's HTTP Negotiate authentication extension. The negotiable submechanisms include NTLM and Kerberos supported by Active Directory. At present HttpClient only supports the Kerberos sub-mechanism.
- Kerberos: Kerberos authentication implementation.
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 the CredentialsProvider interface. The default CredentialsProvider implementation called BasicCredentialsProvider is a simple implementation backed by a java.util.HashMap.
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("somehost", AuthScope.ANY_PORT),
new UsernamePasswordCredentials("u1", "p1"));
credsProvider.setCredentials(
new AuthScope("somehost", 8080),
new UsernamePasswordCredentials("u2", "p2"));
credsProvider.setCredentials(
new AuthScope("otherhost", 8080, AuthScope.ANY_REALM, "ntlm"),
new UsernamePasswordCredentials("u3", "p3")); System.out.println(credsProvider.getCredentials(new AuthScope("somehost", 80, "realm", "basic")));
System.out.println(credsProvider.getCredentials(new AuthScope("somehost", 8080, "realm", "basic")));
System.out.println(credsProvider.getCredentials(new AuthScope("otherhost", 8080, "realm", "basic")));
System.out.println(credsProvider.getCredentials(new AuthScope("otherhost", 8080, null, "ntlm")));
stdout >
[principal: u1]
[principal: u2]
null
[principal: u3]
HTTP Authentication and Execution Context
HttpClient relies on the AuthState class to keep track of detailed information about the state of the authentication process. HttpClient creates two instances of AuthState in the course of HTTP request execution: one for target host authentication and another one for proxy authentication. 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:
- 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:
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());
Caching of Authentication Data
As of version 4.1 HttpClient automatically caches information about hosts it has successfully authenticated with. 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.
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. Therefore, users are expected to evaluate potential benefits of preemptive authentication versus security risks in the context of their specific application environment.
Nonetheless one can configure HttpClient to authenticate preemptively by prepopulating the authentication data cache.
CloseableHttpClient httpclient = <...>
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();
}
}
HttpClient(4.3.5) - HTTP Authentication的更多相关文章
- HttpClient 三种 Http Basic Authentication 认证方式,你了解了吗?
Http Basic 简介 HTTP 提供一个用于权限控制和认证的通用框架.最常用的 HTTP 认证方案是 HTTP Basic authentication.Http Basic 认证是一种用来允许 ...
- Central Authentication Service
国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...
- 一个HTTP Basic Authentication引发的异常
这几天在做一个功能,其实很简单.就是调用几个外部的API,返回数据后进行组装然后成为新的接口.其中一个API是一个很奇葩的API,虽然是基于HTTP的,但既没有基于SOAP规范,也不是Restful风 ...
- httpcomponents-client-4.4.x
Chapter 1. Fundamentals Prev Next Chapter 1. Fundamentals 1.1. Request execution The most essent ...
- httpcomponents-client-ga(4.5)
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/ Chapter 1. Fundamentals Prev Next ...
- httpcomponents-client-4.3.x DOC
Chapter 1. Fundamentals Prev Next Chapter 1. Fundamentals 1.1. Request execution The most essent ...
- Jenkins Slave Nodes – using the Swarm Plugin
link: http://www.donaldsimpson.co.uk/2013/03/18/jenkins-slave-nodes-using-the-swarm-plugin/ I’ve bee ...
- C# Webclient 和 Httpclient如何通过iis authentication 身份验证。
前言: 该博客产生的背景是客户那边有部署网站的方法是iis windows authentication身份验证,而系统中使用Webclient来调用别的系统的方法.在此情况下,原本可以使用的功能,都 ...
- c# HttpClient和HttpWebRequest添加Basic类型的Authentication认证
c#项目中用到调用客户接口,basic身份认证,base64格式加密(用户名:密码)贴上代码以备后用 1.使用HttpClient实现basic身份认证 using (HttpClient clien ...
随机推荐
- UVaLive 6859 Points (几何,凸包)
题意:给定 n 个点,让你用最长的周长把它们严格包围起来,边长只能用小格子边长或者是小格子对角线. 析:先把每个点的上下左右都放到一个集合中,然后求出一个凸包,然后先边长转成题目的方式,也好转两个点的 ...
- myGeneration代码生成器
转自:http://www.cnblogs.com/leitwolf/archive/2007/07/27/833255.html http://blog.csdn.net/happyhippy/ar ...
- thttpd的定时器
运用了static函数实现文件封装 提升变量访问效率的关键字register,该关键字暗示该变量可能被频繁访问,如果可能,请将值存放在寄存器中 内存集中管理,每个节点在取消后并没有立即释放内存,而是调 ...
- Ecshop实现注册页面手机号唯一的验证
前天,公司总监提了一个需求,实现我公司商城注册会员用手机号登录这个功能,那么这个功能容易修改,在我的前一篇博文中已经给出处理方法了,但是这里有一个问题,就是如果实现了用手机号码来登陆,那么就需要在注册 ...
- 通过SCVMM分配SMB 3.0 文件共享
1.创建SMB群集共享,赋予Hyper-V主机. Hyper-V群集名称.Hyper-V管理员.Hyper-V服务账户完全控制权限 2.VMM提供程序导入 文件服务器(运行方式账户要对文件服务器群集的 ...
- ZOJ 1151 Word Reversal反转单词 (string字符串处理)
链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=151 For each list of words, output a l ...
- java笔记-关于一些常用 且实用的开源包
作为一只从.net转java的程序猿..表示有些jdk原生的类很不习惯.. 1.时间处理 代替原生Calendar joda-time 框架.地址https://github.com/JodaOr ...
- Codeforces Gym H. Hell on the Markets 贪心
Problem H. Hell on the MarketsTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vj ...
- 使用IOCTL代码实现LCD背光调节
国内这种代码找不到.于是參考了相关代码后完好例如以下代码,且实现方式通过IOCTL代码实现LCD背光调节的功能. 适合场合为平板电脑或者笔记本.主要还是要靠BIOS支持与否. 编译环境使用:Dev-c ...
- 模式识别 - 处理多演示样例学习(MIL)特征(matlab)
处理多演示样例学习(MIL)特征(matlab) 本文地址: http://blog.csdn.net/caroline_wendy/article/details/27206325 多演示样例学习( ...