Digest Auth 认证

徐涵亮
2023-12-01

本人写的Digest 认证一次通过,不需要按照常规的方式来 

 public void postMethod(String url, String query) {
		  try {

			  CredentialsProvider credsProvider = new BasicCredentialsProvider();
		        credsProvider.setCredentials(
		                new AuthScope("192.168.1.105", 9000),//请求地址 + 端口号
		                new UsernamePasswordCredentials("admin", "admin"));// 用户名 + 密码 (用于验证)
		        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数据需要设置contentType
			  postMethod.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);
			}
		 
		  }

正常认证方式:

  1. 发送一个请求

        GET /auth/basic/ HTTP/1.1
        HOST: target
  2. 服务器返回401响应头,要求输入用户凭据

        HTTP/1.1 401 Unauthorized
        WWW-Authenticate: Digest realm="Digest Encrypt",nonce="nmeEHKLeBAA=aa6ac7ab3cae8f1b73b04e1e3048179777a174b3", opaque="0000000000000000",stale=false, algorithm=MD5, qop="auth"
  3. 输入凭据后再发送请求

        GET /auth/digest/ HTTP/1.1
        Accept: */*
        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. 服务端验证通过后返回数据

 类似资料: