前言
今天工作需要做了摘要认证(digest authentication),下面就工作中遇到的问题及过程做一个总结。
一、四个过程
F1:POST URL
F2: 401 Unauthorized
F3: 根据F2 返回的认证信息,带userName、password进行验证
F4: 返回 状态 200
二、过程细节
1、 第一次客户端请求
GET/POST
2、 服务器产生一个随机数nonce,服务器将这个随机数放在WWW-Authenticate响应头,与服务器支持的认证算法列表,认证的域realm一起发送给客户端,如下例子:
HTTP /1.1 401 Unauthorized
WWW-Authenticate:Digest
realm= ”test realm”
qop=auth,auth-int”
nonce=”66C4EF58DA7CB956BD04233FBB64E0A4”
opaque=“5ccc069c403ebaf9f0171e9517f40e41”
• realm的值是一个简单的字符串
• qop是认证的(校验)方式
• nonce是随机数, 可以用GUID
• opaque是个随机字符串,它只是透传而已,即客户端还会原样返回过来。
• algorithm 是个字符串,用来指示用来产生分类及校验和的算法对。如果该域没指定,则认为是“MD5“算法。
3、 客户端发现是401响应,表示需要进行认证,则弹出让用户输入用户名和密码的认证窗口,客户端选择一个算法,计算出密码和其他数据的摘要(response),将摘要放到Authorization的请求头中发送给服务器,如果客户端要对服务器也进行认证,这个时候,可以发送客户端随机数cnonce。如下例子:
GET/cgi-bin/checkout?a=b HTTP/1.1
Authorization: Digest
username="Mufasa",
realm="realm",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c0", uri="/xxxx/System/Register",
qop=auth, nc=00000001, cnonce="0a4f113b",
response="6629fae49393a05397450978507c4ef1",
opaque="5ccc069c403ebaf9f0171e9517f40e41"
4、 服务接受摘要,选择算法,获取数据库用户名密码,重新计算新的摘要跟客户端传输的摘要进行比较,验证是否匹配。
200 OK
三、HttpClient 代码示例
/**
* 摘要认证 两次请求
*
* @param url
* @return 返回结果
*/
public static Boolean doPostDigest(String url, String username, String password) {
log.info("Post请求url:[{}]", url);
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpPost httpPost = null;
String strResponse = null;
Boolean flag = false;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
// 构造请求头
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.addHeader("Cache-Control", "no-cache"); //设置缓存
httpPost.setHeader("Connection", "Close");
RequestConfig.Builder builder = RequestConfig.custom();
builder.setSocketTimeout(3000); //设置请求时间
builder.setConnectTimeout(5000); //设置超时时间
builder.setRedirectsEnabled(false);//设置是否跳转链接(反向代理)
// 设置 连接 属性
httpPost.setConfig(builder.build());
// 执行请求
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
// 检验返回码
int statusCode = response.getStatusLine().getStatusCode();
log.info("第一次发送摘要认证 Post请求 返回码:{}", statusCode);
if (401 == statusCode) {
strResponse = EntityUtils.toString(responseEntity, "utf-8");
log.info("Post请求401返回结果:{}", strResponse);
// 组织参数,发起第二次请求
Header[] headers = response.getHeaders("WWW-Authenticate");
HeaderElement[] elements = headers[0].getElements();
String realm = null;
String qop = null;
String nonce = null;
String opaque = null;
String method = "POST";
String uri = "/VIID/System/Register";
for (HeaderElement element : elements) {
if (element.getName().equals("Digest realm")) {
realm = element.getValue();
} else if (element.getName().equals("qop")) {
qop = element.getValue();
} else if (element.getName().equals("nonce")) {
nonce = element.getValue();
} else if (element.getName().equals("opaque")) {
opaque = element.getValue();
}
}
// 以上为 获取第一次请求后返回的 数据
String nc = "00000001";
String cnonce = "uniview";
// 后期变成可配置
String a1 = username + ":" + realm + ":" + password;
String a2 = method + ":" + uri;
String response1 = null;
// 获取 Digest 这个字符串
String backString = response.getFirstHeader("WWW-Authenticate").getValue();
try {
response1 = md5DigestAsHex((md5DigestAsHex(a1.getBytes("UTF-8")) + ":" + nonce + ":" + nc
+ ":" + "uniview" + ":" + qop + ":" + md5DigestAsHex(a2.getBytes("UTF-8"))).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
log.error("MD5异常:{}", e.getLocalizedMessage());
}
httpPost.addHeader("Authorization", backString + ",username=\"" + username + "\"" + ",realm=\"" + realm + "\""
+ ",nonce=\"" + nonce + "\"" + ",uri=\"" + uri + "\"" + ",qop=\"" + qop + "\"" + ",nc=\"" + nc + "\""
+ ",cnonce=\"" + cnonce + "\"" + ",response=\"" + response1 + "\"" + ",opaque=\"" + opaque);
// 发送第二次请求
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
int statusCode1 = response.getStatusLine().getStatusCode();
log.info("第二次发送摘要认证 Post请求 返回码:{}");
if (HttpStatus.SC_OK == statusCode1) {
strResponse = EntityUtils.toString(entity, StandardCharsets.UTF_8);
flag = true;
return flag;
} else {
strResponse = EntityUtils.toString(entity, StandardCharsets.UTF_8);
log.error("第二次鉴权认证请求非 200 返回结果:{}", strResponse);
return flag;
}
} else {
strResponse = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
log.error("第一次鉴权认证请求非401 返回结果:{}", strResponse);
}
} catch (Exception e) {
log.error("摘要认证 发送请求失败", e.getLocalizedMessage());
} finally {
if (null != httpPost) {
httpPost.releaseConnection();
}
if (null != response) {
try {
response.close();
} catch (IOException e) {
log.error("httpResponse流关闭异常:", e);
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
log.error("httpClient 流关闭异常:", e);
}
}
}
return flag;
}
public static String encode(String password) {
try {
//获取MD5对象
MessageDigest instance = MessageDigest.getInstance("MD5");
//对字符串进行加密,返回字节数组
byte[] digest = instance.digest(password.getBytes());
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
//获取字节低八位有效值
int i = b & 0xff;
//将整数转换为16进制
String hexString = Integer.toHexString(i);
//将长度为1时,补零
if (hexString.length() < 2) {
hexString = "0" + hexString;
}
//MD5永远是32位
sb.append(hexString);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
//没有该算法时抛出此异常
e.printStackTrace();
}
return "";
}