JAVA 接口基础认证
2024-07-04
1. Basic认证
HttpHeaders headers = new HttpHeaders();
String auth = ParameterUtil.getImageServerUser() + ":" + ParameterUtil.getImageServerPassword();
byte[] encodedAuth = Base64.encode(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String( encodedAuth );
headers.set("Authorization", authHeader );
HttpEntity<String> entity = new HttpEntity<String>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("http://"+ParameterUtil.getImageServerHost()+":"+ParameterUtil.getImageServerPort()+"/ims/external/"+imsurl+"?filePath=" + filePath + "&fileName=" + fileName, entity, String.class);
return stringResponseEntity.getBody();
2. HMAC 认证
2.1 直接使用
@SneakyThrows
private HttpHeaders getDpsHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
Map<String, String> m = SignatureClient.hmacSignature(ak, sk, "");
// 获取值
String contentType = "application/json";
String authorization = m.get("Authorization");
String date = m.get("Date");
String md5 = m.get("Content-md5");
headers.add("Content-Type", contentType);
headers.add("Authorization", authorization);
headers.add("Date", date);
headers.add("Content-md5", md5);
return headers;
}
SignatureClient
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
public class SignatureClient {
private static final String HMAC_SHA1 = "HMACSHA1";
public SignatureClient() {
}
public static Map<String, String> hmacSignature(String AK, String SK, String content) throws Exception {
Map<String, String> returnMap = new HashMap();
Date now = new Date();
String gmtdate = getGMT(now);
String content_Md5 = "";
try {
content_Md5 = EncoderByMd5(content);
} catch (Exception var11) {
throw new Exception("Content MD5 Failed");
}
String signature = "";
String signstring = "date: " + gmtdate + "\ncontent-md5: " + content_Md5;
try {
signature = getSignature(signstring, SK);
} catch (Exception var10) {
throw new Exception("SK signature Failed");
}
String auth = "hmac accesskey=\"" + AK + "\", algorithm=\"hmac-sha1\", headers=\"date content-md5\", signature=\"" + signature + "\"";
returnMap.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
returnMap.put("Authorization", auth);
returnMap.put("Date", gmtdate);
returnMap.put("Content-md5", content_Md5);
return returnMap;
}
private static String getGMT(Date dateCST) {
DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df.format(dateCST);
}
private static String EncoderByMd5(String str) throws Exception {
String md5Str = DigestUtils.md5Hex(str);
String base64_str = Base64.encodeBase64String(md5Str.getBytes("utf-8"));
return base64_str;
}
private static String getSignature(String data, String key) throws Exception {
byte[] keyBytes = key.getBytes("utf-8");
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HMACSHA1");
DigestUtils.sha1Hex(key.getBytes("utf-8"));
Mac mac = Mac.getInstance("HMACSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
String base64_str = Base64.encodeBase64String(rawHmac);
return base64_str;
}
}
2.2 编写工具类
String url = "http://xxxxx";
String ak = "";
String sk = "";
HttpHeaders headers = RestUtil.getHttpHeaders(ak,sk);
HttpEntity<String> request = new HttpEntity<>("", headers); // 请求体为空
//发送请求
ResponseEntity<String> resStr = restTemplate.postForEntity(url, request, String.class);
RestUtil 工具类
/**
* rest请求工具类
*/
public class RestUtil {
/**
* 网关访问在header中需要ak,sk的加密
* @return HttpHeaders
*/
@SneakyThrows(Exception.class)
public static HttpHeaders getHttpHeaders(String ak, String sk) {
Map<String, String> headerParameters = SignatureClient.hmacSignature(ak, sk, "");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headerParameters.forEach(headers::add);
return headers;
}
/**
* 网关访问在header中需要ak,sk的加密
* @return HttpHeaders
*/
@SneakyThrows(Exception.class)
public static HttpHeaders getHttpJsonHeaders(String ak, String sk) {
Map<String, String> headerParameters = SignatureClient.hmacSignature(ak, sk, "");
headerParameters.put(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headerParameters.forEach(headers::add);
return headers;
}
}