![](https://img2023.cnblogs.com/blog/1277216/202304/1277216-20230413142812084-6458205.png)
HttpHeaders headers = new HttpHeaders();
//设置header,此处省略
HttpEntity<Object> entity = new HttpEntity<>("此处放你携带的参数", headers);
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl + "/API/Register", entity, String.class);
if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
List<String> authorizationHeader = response.getHeaders().get("WWW-Authenticate");
String authHeader = authorizationHeader.get(0);
//重新设置请求头
headers.set("Authorization", getHeader(authHeader));
entity = new HttpEntity<>(object, headers);
response = restTemplate.postForEntity(serverUrl + "/API/Register", entity, String.class);
if (response.getStatusCode() == HttpStatus.OK){
//此处写你的方法
}
}
//getHeader方法如下, 此处要根据接收方返回的认证机制选择方法,此处是Digest
public static String getHeader(String authHeader){
String[] parts = authHeader.split(",\\s*");
String realm = null;
String qop = null;
String nonce = null;
//从接收方返回的参数中分离出realm, qop, nonce
for (String part : parts) {
if (part.startsWith("Digest realm=")) {
realm = part.substring("Digest realm=".length()).replace("\"", "");
} else if (part.startsWith("qop=")) {
qop = part.substring("qop=".length()).replace("\"", "");
} else if (part.startsWith("nonce=")) {
nonce = part.substring("nonce=".length()).replace("\"", "");
}
}
String uri = "/API/Register";
//md5进行加密,分两步
String ha1 = DigestUtils.md5Hex(username + ":" + realm + ":" + password);
String ha2 = DigestUtils.md5Hex("POST:"+uri);
String nc = "00000001";
String cnonce = CnonceGenerator.generateCnonce(); // 获取客户端随机数的方法略
String response = DigestUtils.md5Hex(
ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2);
String result = String.format("Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", " +
"qop=\"%s\", nc=\"%s\", cnonce=\"%s\", response=\"%s\"", username, realm, nonce, uri,
qop, nc, cnonce, response);
return result;
}
Digest的优点:
- 不适应明文传输密码
- 防止恶意的重放攻击
- 防止对报文内容的篡改
本文来自博客园,作者:哈利波特甜,转载请注明原文链接:https://www.cnblogs.com/zmh-980509/p/17315173.html