Digest Auth 摘要认证

article/2025/11/8 15:57:14

Digest Auth 摘要认证

1.非常规方式

转载:https://blog.csdn.net/qq_25391785/article/details/86595529

    public static void postMethod(String url, String query) {try {CredentialsProvider credsProvider = new BasicCredentialsProvider();credsProvider.setCredentials(new AuthScope("xx.xx.xx.xx", 80),//请求地址 + 端口号new UsernamePasswordCredentials("xx", "xxxx"));// 用户名 + 密码 (用于验证)CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();HttpPost postMethod = new HttpPost(url);//请求详细地址(如:http://192.168.1.105:9000/MotorVehicles)StringEntity s = new StringEntity(query);//向后台传的json数据s.setContentEncoding("utf-8");//编码s.setContentType("application/json");//发送json数据需要设置contentTypepostMethod.setEntity(s);HttpResponse response = httpclient.execute(postMethod); //执行POST方法System.out.println("resCode = " + response.getStatusLine().getStatusCode()); //获取响应码System.out.println("result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容} catch (Exception e) {System.out.println("推送失败:"+e);}}

2.常规认证方式

在这里插入图片描述
1.发送一个请求

    GET /auth/basic/ HTTP/1.1HOST: target

2.服务器返回401响应头,要求输入用户凭据

    HTTP/1.1 401 UnauthorizedWWW-Authenticate: Digest realm="Digest Encrypt",nonce="nmeEHKLeBAA=aa6ac7ab3cae8f1b73b04e1e3048179777a174b3", opaque="0000000000000000",stale=false, algorithm=MD5, qop="auth"

3.输入凭据后再发送请求

    GET /auth/digest/ HTTP/1.1Accept: */*Authorization:  Digest username="LengWa", realm="Digest Encrypt",  qop="auth", algorithm="MD5", uri="/auth/digest/", nonce="nmeEHKLeBAA=aa6ac7ab3cae8f1b73b04e1e3048179777a174b3", nc=00000001, cnonce="6092d3a53e37bb44b3a6e0159974108b", opaque="0000000000000000", response="652b2f336aeb085d8dd9d887848c3314"

4.服务端验证通过后返回数据

代码工具类(本人的实际服务因第二次传的凭据不返回realm参数,遂在代码里将其写死):


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.asiainfo.req.DigestAuthReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** Http Digest Request contains POST、GET、PUT* @author zhangdan* @date 2021-04-22*/
@Slf4j
public class HttpRequestUtils {private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);public static void main(String[] args) {//        String param = "";
//        String username = "xxxx";
//        String password = "xxxx";postMethod("http://ip:80/api/howell/ver10/aiop_service/garbage_management/GarbageStations/Cameras/List","{\n" +"    \"PageIndex\":\"1\",\n" +"    \"PageSize\":\"99999\"\n" +"}");//System.out.println(s);}static int nc = 0;    //调用次数private static final String GET = "GET";private static final String POST = "POST";private static final String PUT = "PUT";private static final String DELETE = "DELETE";/*** 向指定URL发送POST方法的请求* @param url                                       发送请求的URL* @param param                                     请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @param username                                  验证所需的用户名* @param password                                  验证所需的密码* @param json                                      请求json字符串* @param type                                      返回xml和json格式数据,默认xml,传入json返回json数据* @return URL 所代表远程资源的响应结果*/public  static String sendPost(DigestAuthReq digestAuthReq) {StringBuilder result = new StringBuilder();String json= digestAuthReq.getJsonStr();String url= digestAuthReq.getUrl();String param= digestAuthReq.getParam();String username=digestAuthReq.getUsername();String password=digestAuthReq.getPassword();String type= digestAuthReq.getType();logger.info("json============="+json);BufferedReader in = null;try {//String wwwAuth = sendGet(url, param);       //发起一次授权请求String wwwAuth=sendPost(url, param);if (wwwAuth.startsWith("WWW-Authenticate:")) {wwwAuth = wwwAuth.replaceFirst("WWW-Authenticate:", "");} else {return wwwAuth;}nc ++;String urlNameString = url + (StringUtils.isNotEmpty(param) ? "?" + param : "");URL realUrl = new URL(urlNameString);// 打开和URL之间的连接HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();// 设置是否向connection输出,因为这个是post请求,参数要放在// http正文内,因此需要设为trueconnection.setDoOutput(true);// Read from the connection. Defaultis true.connection.setDoInput(true);// 默认是 GET方式connection.setRequestMethod(POST);// Post 请求不能使用缓存connection.setUseCaches(false);// 设置通用的请求属性setRequestProperty(connection, wwwAuth,realUrl, username, password, POST, type);if (!StringUtils.isEmpty(json)) {byte[] writebytes =json.getBytes();connection.setRequestProperty("Content-Length",String.valueOf(writebytes.length));OutputStream outwritestream = connection.getOutputStream();outwritestream.write(json.getBytes());outwritestream.flush();outwritestream.close();}if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) {in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result.append(line);}} else {String errResult = formatResultInfo(connection, type);logger.info(errResult);return errResult;}nc = 0;} catch (Exception e) {nc = 0;throw new RuntimeException(e);} finally {try {if (in != null) in.close();} catch (Exception e2) {e2.printStackTrace();}}return result.toString();}/*** 向指定URL发送GET方法的请求* @param url                                       发送请求的URL* @param param                                     请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @param username                                  验证所需的用户名* @param password                                  验证所需的密码* @param type                                      返回xml和json格式数据,默认xml,传入json返回json数据* @return URL 所代表远程资源的响应结果*/public static String sendGet(String url, String param, String username, String password, String type) {StringBuilder result = new StringBuilder();BufferedReader in = null;try {String wwwAuth = sendGet(url, param);       //发起一次授权请求if (wwwAuth.startsWith("WWW-Authenticate:")) {wwwAuth = wwwAuth.replaceFirst("WWW-Authenticate:", "");} else {return wwwAuth;}nc ++;String urlNameString = url + (StringUtils.isNotEmpty(param) ? "?" + param : "");URL realUrl = new URL(urlNameString);// 打开和URL之间的连接HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();// 设置通用的请求属性setRequestProperty(connection, wwwAuth,realUrl, username, password, GET, type);// 建立实际的连接// connection.connect();in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result.append(line);}nc = 0;} catch (Exception e) {nc = 0;throw new RuntimeException(e);} finally {try {if (in != null) in.close();} catch (Exception e2) {e2.printStackTrace();}}return result.toString();}/*** 生成授权信息* @param authorization                             上一次调用返回401的WWW-Authenticate数据* @param username                                  用户名* @param password                                  密码* @return                                          授权后的数据, 应放在http头的Authorization里* @throws IOException                              异常*/private static String getAuthorization(String authorization, String uri, String username, String password, String method) throws IOException {uri = StringUtils.isEmpty(uri) ? "/" : uri;String temp = authorization.replaceFirst("Digest", "").trim().replace("MD5","\"MD5\"").replace("realm=\"\"","realm=\"/howell/ver10/data\"");String json = withdrawJson(authorization);JSONObject jsonObject = JSON.parseObject(json);String cnonce = Digests.generateSalt2(8);String ncstr = ("00000000" + nc).substring(Integer.toString(nc).length());     //认证的次数,第一次是1,第二次是2...String algorithm = jsonObject.getString("algorithm");String qop = jsonObject.getString("qop");String nonce = jsonObject.getString("nonce");String realm = jsonObject.getString("realm");if(StringUtils.isEmpty(realm)){realm="/howell/ver10/data";}String response = Digests.http_da_calc_HA1(username, realm, password,nonce, ncstr, cnonce, qop,method, uri, algorithm);//组成响应authorizationauthorization = "Digest username=\"" + username + "\"," + temp;authorization += ",uri=\"" + uri+ "\",nc=\"" + ncstr+ "\",cnonce=\"" + cnonce+ "\",response=\"" + response+"\"";return authorization;}/*** 将返回的Authrization信息转成json* @param authorization                                     authorization info* @return                                                  返回authrization json格式数据 如:String json = "{ \"realm\": \"Wowza\", \" domain\": \"/\", \" nonce\": \"MTU1NzgxMTU1NzQ4MDo2NzI3MWYxZTZkYjBiMjQ2ZGRjYTQ3ZjNiOTM2YjJjZA==\", \" algorithm\": \"MD5\", \" qop\": \"auth\" }";*/private static String withdrawJson(String authorization) {String temp = authorization.replaceFirst("Digest", "").trim().replaceAll("\"","");String[] split = temp.split(",");Map<String, String> map = new HashMap<>();Arrays.asList(split).forEach(c -> {String c1 = c.replaceFirst("=",":");String[] split1 = c1.split(":");if(split1[0].trim().equals("realm")){map.put(split1[0].trim(), "/howell/ver10/data");}else{map.put(split1[0].trim(), split1[1].trim());}});return JSONObject.toJSONString(map);}/*** 向指定URL发送GET方法的请求* @param url                                                   发送请求的URL* @param param                                                 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return URL                                                  所代表远程资源的响应结果*/public static String sendGet(String url, String param) {StringBuilder result = new StringBuilder();BufferedReader in = null;try {String urlNameString = url + (StringUtils.isNotEmpty(param) ? "?" + param : "");URL realUrl = new URL(urlNameString);// 打开和URL之间的连接URLConnection connection = realUrl.openConnection();// 设置通用的请求属性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");connection.connect();//返回401时需再次用用户名和密码请求//此情况返回服务器的 WWW-Authenticate 信息if (((HttpURLConnection) connection).getResponseCode() == 401) {Map<String, List<String>> map = connection.getHeaderFields();return "WWW-Authenticate:" + map.get("WWW-Authenticate").get(0);}in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result.append(line);}} catch (Exception e) {throw new RuntimeException("get请求发送失败",e);}// 使用finally块来关闭输入流finally {try {System.out.println(result.toString());if (in != null) in.close();} catch (Exception e2) {e2.printStackTrace();}}System.out.println(result.toString());logger.info(result.toString());return result.toString();}/*** 向指定URL发送GET方法的请求* @param url                                                   发送请求的URL* @param param                                                 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return URL                                                  所代表远程资源的响应结果*/public static String sendPost(String url, String parameters ) {String result = "";BufferedReader in = null;try {String ip = "124.71.147.146";Integer port = 80;String username="wujiaochang";String password="3EhcqnbnZ4QFJ9sk";int resCode = 404;CredentialsProvider credsProvider = new BasicCredentialsProvider();credsProvider.setCredentials(new AuthScope(ip, port), // 请求地址 + 端口号new UsernamePasswordCredentials(username, password));// 用户名 + 密码 (用于验证)HttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();try {SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();} catch (Exception e) {e.printStackTrace();}HttpPost postMethod = new HttpPost(url);// 请求详细地址(如:http://192.168.1.105:9000/MotorVehicles)//根据不通要求自己添加头//根据不通要求自己添加头postMethod.addHeader("Content-Type", "application/json");postMethod.addHeader("accept", "*/*");postMethod.addHeader("connection", "Keep-Alive");postMethod.addHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");StringEntity s = new StringEntity(JSON.toJSONString(parameters));// 向后台传的json数据s.setContentEncoding("utf-8");// 编码postMethod.setEntity(s);HttpResponse response = httpclient.execute(postMethod); // 执行POST方法resCode = response.getStatusLine().getStatusCode();System.out.println("resCode = " + resCode); // 获取响应码result = EntityUtils.toString(response.getEntity(), "utf-8");log.info("result = " + result); // 获取响应内容if (resCode == 401) {return  "" +response.getHeaders("WWW-Authenticate")[0];}}// 使用finally块来关闭输入流catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}System.out.println(result.toString());logger.info(result.toString());return result.toString();}/*** HTTP set request property** @param connection                            HttpConnection* @param wwwAuth                               授权auth* @param realUrl                               实际url* @param username                              验证所需的用户名* @param password                              验证所需的密码* @param method                                请求方式* @param type                                  返回xml和json格式数据,默认xml,传入json返回json数据*/private static void setRequestProperty(HttpURLConnection connection, String wwwAuth, URL realUrl, String username, String password, String method, String type)throws IOException {if (type != null && type.equals("json")) {// 返回jsonconnection.setRequestProperty("X-Webbrowser-Authentication","Forbidden");connection.setRequestProperty("accept", "application/json;charset=UTF-8");connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");} else {// 返回xmlif (!method.equals(GET)) {connection.setRequestProperty("X-Webbrowser-Authentication","Forbidden");connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");}connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");// connection.setRequestProperty("Cache-Control", "no-cache");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");}//授权信息String authentication = getAuthorization(wwwAuth, realUrl.getPath(), username, password, method);connection.setRequestProperty("Authorization", authentication);}/*** 格式化请求返回信息,支持json和xml格式* @param connection                                HttpConnection* @param type                                      指定返回数据格式,json、xml,默认xml* @return                                          返回数据*/private static String formatResultInfo(HttpURLConnection connection, String type) throws IOException {String result = "";if (type != null && type.equals("json")) {result = String.format("{\"errCode\":%s, \"message\":%s}",connection.getResponseCode(),connection.getResponseMessage());} else {result = String.format(" <?xml version=\"1.0\" encoding=\"UTF-8\" ?> "+ " <wmsResponse>"+ " <errCode>%d</errCode>"+ " <message>%s</message>"+ " </wmsResponse>",connection.getResponseCode(),connection.getResponseMessage());}return result;}}

http://chatgpt.dhexx.cn/article/8XRhWnte.shtml

相关文章

digest鉴权

“摘要”式认证&#xff08; Digest authentication&#xff09;是一个简单的认证机制&#xff0c;最初是为HTTP协议开发的&#xff0c;因而也常叫做HTTP摘要&#xff0c;在RFC2671中描述。其身份验证机制很简单&#xff0c;它采用杂凑式&#xff08;hash&#xff09;加密方法&…

消息摘要(Digest),数字签名(Signature),数字证书(Certificate)是什么?

1. 消息摘要&#xff08;Digest&#xff09; 1. 什么是消息摘要&#xff1f; 对一份数据&#xff0c;进行一个单向的 Hash 函数&#xff0c;生成一个固定长度的 Hash 值&#xff0c;这个值就是这份数据的摘要&#xff0c;也称为指纹。 2. 摘要算法 常见的摘要算法有 MD5、SHA…

HTTP通讯安全中的Digest摘要认证释义与实现

摘要 出于安全考虑&#xff0c;HTTP规范定义了几种认证方式以对访问者身份进行鉴权&#xff0c;最常见的认证方式之一是Digest认证 Digest认证简介 HTTP通讯采用人类可阅读的文本格式进行数据通讯&#xff0c;其内容非常容易被解读。出于安全考虑&#xff0c;HTTP规范定义了几…

http协议之digest(摘要)认证,详细讲解并附Java SpringBoot源码

目录 1.digest认证是什么&#xff1f; 2.digest认证过程 3.digest认证参数详解 4.基于SpringBoot实现digest认证 5.digest认证演示 6.digest认证完整项目 7.参考博客 1.digest认证是什么&#xff1f; HTTP通讯采用人类可阅读的文本格式进行数据通讯&#xff0c;其内容非…

【WinRAR】WinRAR 6.01 官方最新简体中文版

WinRAR 6.01 官方简体中文商业版下载地址&#xff08;需要注册&#xff09;&#xff1a; 64位&#xff1a; https://www.win-rar.com/fileadmin/winrar-versions/sc/sc20210414/wrr/winrar-x64-601sc.exe https://www.win-rar.com/fileadmin/winrar-versions/sc/sc20210414/…

WinRAR命令行

基本使用 实践 将文件夹压缩到zip包 输入&#xff1a;文件夹如下&#xff0c;文件夹为class。 输出&#xff1a;classes.zip 指令如下&#xff1a; rar a classes.zip .\classes或者 WinRAR a classes.zip .\classes结果如下&#xff1a; PS C:\Users\liyd\Desktop\kuai…

WinRAR安装教程

文章目录 WinRAR安装教程无广告1. 下载2. 安装3. 注册4. 去广告 WinRAR安装教程无广告 1. 下载 国内官网&#xff1a;https://www.winrar.com.cn/ 2. 安装 双击&#xff0c;使用默认路径&#xff1a; 点击“安装”。 点击“确定”。 点击“完成”。 3. 注册 链接&#x…

WinRAR注册+去广告教程

1、注册 在WinRAR安装目录创建rarreg.key文件&#xff0c; 拷贝如下内容并保存&#xff1a; RAR registration data Federal Agency for Education 1000000 PC usage license UIDb621cca9a84bc5deffbf 6412612250ffbf533df6db2dfe8ccc3aae5362c06d54762105357d 5e3b1489e751c…

WinRAR4.20注册文件rarreg.key

2019独角兽企业重金招聘Python工程师标准>>> 在WinRAR的安装目录下&#xff0c;新建rarreg.key文件&#xff08;注意不要创建成rarreg.key.txt文件了^_^&#xff09;&#xff0c;内容为如下&#xff1a; RAR registration data Team EAT Single PC usage license UI…

Android按钮样式

//创建一个新的XML文件&#xff0c;可命名为styles<style name"button1"><item name"android:layout_height">wrap_content</item><item name"android:textColor">#FFFFFF</item><item name"android:text…

漂亮的Button按钮样式

开发中各种样式的Button,其实这些样式所有的View都可以共用的,可能对于你改变的只有颜色 所有的都是用代码实现 边框样式,给你的View加上边框 <Buttonandroid:layout_width="0dip"android:layout_height="match_parent"android:layout_margin=&q…

「HTML+CSS」--自定义按钮样式【001】

前言 Hello&#xff01;小伙伴&#xff01; 首先非常感谢您阅读海轰的文章&#xff0c;倘若文中有错误的地方&#xff0c;欢迎您指出&#xff5e; 哈哈 自我介绍一下 昵称&#xff1a;海轰 标签&#xff1a;程序猿一只&#xff5c;C选手&#xff5c;学生 简介&#xff1a;因C语…

HTML_炫酷的按钮样式

html部分 <a href"#"><span></span><span></span><span></span><span></span>Neon button</a><a href"#"><span></span><span></span><span></span…

html改变按钮样式

今天有人问我怎么改样式&#xff0c;需求是三个按钮&#xff0c;一次点一个&#xff0c;要求被点击的按钮和没被点的按钮是两种不同的样式&#xff0c;如图所示。 最初三个按钮都没选如图一&#xff0c;然后点击“已读”按钮&#xff0c;“已读”按钮样式改变。再点击“全部”按…

button按钮的一些样式效果

先制作一个button按钮 &#xff0c;将它原本的样式取消掉再把button按钮的颜色设置成transparent &#xff0c;再设置button按钮的边框。首先将button按钮的初始样式取消掉 &#xff0c;在设置button按钮的width和 height &#xff0c;font-size &#xff0c;还有border 现在写…

vue点击按钮改变按钮样式

一. 效果 点击按钮前&#xff1a; 点击按钮后&#xff1a; 再次点击按钮变回原来的样式&#xff1a; 二. 具体代码 <template><div id"box"><button click"btn" id"but" v-bind:class"{ but01: style1, but02: style2 }&qu…

CSS 按钮button美化

.login-button { /* 按钮美化 */width: 270px; /* 宽度 */height: 40px; /* 高度 */border-width: 0px; /* 边框宽度 */border-radius: 3px; /* 边框半径 */background: #1E90FF; /* 背景颜色 */cursor: pointer; /* 鼠标移入按钮范围时出现手势 */outline: none; /* 不显示轮廓…

css 按钮按下样式

在项目开发中&#xff0c;按钮通常需要添加按钮的获得焦点状态&#xff0c;电脑端用 :hover 移动端用 :active 。多个按钮需要添加时&#xff0c;就得添加多个获得焦点样式。 可通过添加背景图片的方式来给所有的按钮添加样式&#xff0c;该样式会给当前按钮添加一个白色的透明…

button样式设置:按钮按压效果

在学习MVC基础时&#xff0c;里面的案例有很多都是有按钮的&#xff0c; 但button的默认样式不好看&#xff0c;于是设置了按钮的样式&#xff0c;按 钮按压时有一种现实生活中按钮向下压的效果&#xff0c;这样看起来 非常美观&#xff0c;代码也是不多&#xff0c;简单而又实…

Button按钮的元素与样式改变

作者&#xff1a;李坤凤 本次任务完成时间&#xff1a;2019年6月22日 开发工具与关键技术&#xff1a;开发工具&#xff1a;VS 关键技术: Button按钮的元素与样式改变 1、在button元素中&#xff0c;原始的元素就是一个没有任何样式的按钮&#xff0c;直接使用感觉一点美感没有…