摘要认证,使用HttpClient实现HTTP digest authentication

前言

今天工作需要做了摘要认证(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“算法。

  1. 客户端发现是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"

  1. 服务接受摘要,选择算法,获取数据库用户名密码,重新计算新的摘要跟客户端传输的摘要进行比较,验证是否匹配。
    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 "";
    }
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
HttpClient可以通过提供的CredentialsProvider接口来实现digest认证。下面是一个示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.DigestScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class DigestAuthExample { public static void main(String[] args) throws IOException { String username = "user"; String password = "password"; HttpHost target = new HttpHost("localhost", 8080, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpClient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); HttpClientContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet("/"); CloseableHttpResponse response = httpClient.execute(target, httpGet, context); try { HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } finally { response.close(); } // Get the digest scheme from the context DigestScheme digestScheme = (DigestScheme) context.getAuthScheme(target); // Use the digest scheme to generate the next request's headers HttpGet httpGet2 = new HttpGet("/"); httpGet2.addHeader(digestScheme.authenticate( new UsernamePasswordCredentials(username, password), httpGet2, context)); CloseableHttpResponse response2 = httpClient.execute(target, httpGet2, context); try { HttpEntity entity = response2.getEntity(); EntityUtils.consume(entity); } finally { response2.close(); } } } ``` 这个示例代码中,使用了BasicCredentialsProvider来提供用户名和密码。当httpClient执行第一次请求时,服务器返回401 Unauthorized响应,httpClient会尝试使用提供的凭据进行认证。然后,httpClient使用DigestScheme生成下一个请求的摘要认证头。在第二次请求中,httpClient使用这个头来进行认证

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java冯坚持

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值