app接口。新增了两个接口
This commit is contained in:
@@ -2,9 +2,13 @@ package com.example.caseData.extend.app;
|
||||
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpResponse;
|
||||
import com.example.caseData.exception.BusinessException;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
@@ -119,4 +123,45 @@ public class Base {
|
||||
return response.body();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验签名
|
||||
* @param request 请求对象
|
||||
* @param secretKey 密钥
|
||||
* @param mapper ObjectMapper 实例(用于 JSON 反序列化)
|
||||
*/
|
||||
public static void checkSign(HttpServletRequest request, String secretKey, ObjectMapper mapper) {
|
||||
try {
|
||||
String appId = request.getHeader("appId");
|
||||
String sign = request.getHeader("sign");
|
||||
|
||||
if (appId == null || appId.isEmpty()) {
|
||||
throw new BusinessException("-1", "请求未授权");
|
||||
}
|
||||
if (sign == null || sign.isEmpty()) {
|
||||
throw new BusinessException("-1", "缺少签名");
|
||||
}
|
||||
|
||||
// 读取请求体
|
||||
String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
|
||||
if (body == null || body.isEmpty()) {
|
||||
throw new BusinessException("-1", "请求体为空");
|
||||
}
|
||||
|
||||
// 使用 TypeReference 明确泛型类型,避免警告
|
||||
Map<String, Object> params = mapper.readValue(body, new TypeReference<Map<String, Object>>() {});
|
||||
|
||||
// 生成签名
|
||||
String serverSign = Base.genSignature(params, secretKey);
|
||||
|
||||
if (!sign.equals(serverSign)) {
|
||||
throw new BusinessException("-1", "签名错误");
|
||||
}
|
||||
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("-1", "签名校验失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user