我的小程序接口被刷爆了
/**
* sign校验拦截器
* @author JJ
*/
@Slf4j
@Component
public class CheckSignInterceptor implements HandlerInterceptor {
private static final String SecretKey = "*******";
// 签名过期时间(s)
private static final Integer TimestampOut = 300;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
RequestWrapper requestWrapper = new RequestWrapper(request);
String body = requestWrapper.getBody();
Result result = this.check(body);
if (!result.getSuccess()) {
log.info("签名失败:{}", body);
// 设置状态码为401,表示未授权
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
// 设置响应内容类型和字符集
response.setContentType("application/json;charset=UTF-8");
// 自定义输出
response.getWriter().write(JSONUtil.toJsonStr(result));
// 返回false阻止后续处理
return false;
}
return true;
}
/**
* token校验
* @param token
* @return
*/
private Result check(String body) {
JSONObject jsonObject = JSONUtil.parseObj(body);
String sign = "";
Long timestamp = 0L;
// jsonObject 值输入有序列表。
List<String> paramsValueList = new ArrayList<>();
Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.equals("sign")){
sign = value.toString();
continue;
}
if (key.equals("timestamp")){
//如果时间戳为空
if (Strings.isNullOrEmpty(value.toString())){
return Result.failed(ErrorCodeEnum.ILLEGAL_ARGUMENT.code(), "时间戳不能为空");
}
timestamp = Long.parseLong(value.toString());
}
paramsValueList.add(value.toString());
}
paramsValueList.add(SecretKey);
Collections.sort(paramsValueList);
//判断时间是否大于5分钟
if (System.currentTimeMillis()/1000 - timestamp > TimestampOut){
//return Result.failed(ErrorCodeEnum.ILLEGAL_ARGUMENT.code(), "时间戳无效");
}
String signStr = "";
for (String value : paramsValueList) {
signStr += value;
}
log.info("signStr:{}", signStr);
String sha1Str = SecureUtil.sha1(signStr);
if (sha1Str.equals(sign)){
return Result.success();
}
return Result.failed(ErrorCodeEnum.ILLEGAL_ARGUMENT.code(), "签名失败");
}
}