重构请求 自定义注解 接口验签
定义注解
package com.jianmu.config.request.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SafetyApi {
long expireTime() default 2000;
long repeatTime() default 3000;
boolean encrypt() default false;
}
package com.jianmu.config.request.anno;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class Safety {
private String uri;
private Long expireTime;
private Long repeatTime;
private Boolean encrypt;
}
package com.jianmu.config.request.anno;
import com.jianmu.tools.AnnotationTools;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
public class SafetyConstant {
public static final List<Safety> URIS;
static {
URIS = AnnotationTools.findUrisByAnnoScan("com.jianmu.api", RestController.class, SafetyApi.class);
}
private SafetyConstant() {
}
}
包装HttpServletRequest,目的是让其输入流可重复读
package com.jianmu.config.request;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
@Slf4j
public class RefactorRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public RefactorRequestWrapper(HttpServletRequest request, byte[] body) {
super(request);
this.body = body;
}
@Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() {
return inputStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}
重构请求 并验签
RSA 前端用公钥加密的数据 后端用私钥解密
package com.jianmu.config.request;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jianmu.config.RsaConfig;
import com.jianmu.config.request.anno.Safety;
import com.jianmu.config.request.anno.SafetyConstant;
import com.jianmu.exception.MessagePromptException;
import com.jianmu.tools.ApiTools;
import com.jianmu.tools.EncryptTools;
import com.jianmu.tools.Md5Tools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@WebFilter
@Slf4j
@Component
public class RefactorRequestFilter implements Filter {
private final RsaConfig rsaConfig;
private final RedisTemplate<String, Object> redisTemplate;
private final HandlerExceptionResolver handlerExceptionResolver;
private Safety safety;
@Autowired
public RefactorRequestFilter(RsaConfig rsaConfig, RedisTemplate<String, Object> redisTemplate, HandlerExceptionResolver handlerExceptionResolver) {
this.rsaConfig = rsaConfig;
this.redisTemplate = redisTemplate;
this.handlerExceptionResolver = handlerExceptionResolver;
}
public String getBodyString(ServletRequest request) {
StringBuilder sb = new StringBuilder();
try (InputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
log.error(e.getMessage());
}
return sb.toString();
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (CollectionUtils.isNotEmpty(SafetyConstant.URIS)) {
this.safety = SafetyConstant.URIS.parallelStream().filter(i -> i.getUri().contains(request.getRequestURI())).findFirst().orElse(null);
}
if (CollectionUtils.isNotEmpty(SafetyConstant.URIS) && Objects.nonNull(this.safety)) {
if (log.isDebugEnabled()) {
log.debug("需要安全验证的api:{}", request.getRequestURI());
}
byte[] data;
try {
JSONObject paramJson = JSON.parseObject(this.getBodyString(request));
if (log.isDebugEnabled()) {
log.debug("数据加密密文:{}", paramJson.toJSONString());
}
if (this.safety.getEncrypt()) {
final String encrypt = paramJson.getString("b");
if (encrypt == null) {
throw new MessagePromptException("数据异常");
}
paramJson.put("b", EncryptTools.decrypt(rsaConfig.getPrivateKey(), encrypt));
}
if (log.isDebugEnabled()) {
log.debug("数据加密解文:{}", paramJson);
}
data = handler(paramJson);
} catch (Exception e) {
log.error("error:", e);
handlerExceptionResolver.resolveException(request, response, null, new MessagePromptException(e.getMessage()));
return;
}
chain.doFilter(new RefactorRequestWrapper(request, data), response);
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
private byte[] handler(JSONObject params) throws MessagePromptException {
JSONObject b = params.getJSONObject("b");
final long timestamp = b.getLongValue("t");
final String sign = b.getString("s");
JSONObject p = JSON.parseObject(b.getString("p"));
p.put("gp", EncryptTools.aesDecrypt(p.getString("gp")));
this.isExpired(timestamp);
this.isSign(b);
this.isRepeatSubmit(sign, this.safety.getExpireTime());
p.put("v", params.getString("v"));
final String ps = p.toJSONString();
if (log.isDebugEnabled()) {
log.debug("业务参数:{}", ps);
}
return ps.getBytes();
}
private void isExpired(final long timestamp) throws MessagePromptException {
final long currentTime = System.currentTimeMillis();
final long requestInterval = currentTime - timestamp;
if (requestInterval > Optional.ofNullable(this.safety.getExpireTime()).orElseThrow(() -> new MessagePromptException("请求异常"))) {
log.error("请求超时时间:{},当前时间:{},超时:{}", currentTime, timestamp, requestInterval);
throw new MessagePromptException("请求超时");
}
}
private void isSign(final JSONObject dataJson) throws MessagePromptException {
final String signStr = ApiTools.concatSignString(dataJson.getInnerMap());
final String serverSign = Md5Tools.encode(signStr);
final String sign = dataJson.getString("s");
final boolean flag = serverSign.equals(sign);
if (log.isDebugEnabled()) {
log.debug("签名数据:{}", JSON.toJSONString(dataJson.getInnerMap()));
log.debug("签名字符串:{}", signStr);
log.debug("签名1:{}", serverSign);
log.debug("签名2:{}", sign);
}
if (!flag) {
throw new MessagePromptException("签名错误");
}
}
private void isRepeatSubmit(final String sign, final long expireTime) throws MessagePromptException {
ValueOperations<String, Object> signRedis = redisTemplate.opsForValue();
final boolean exists = Optional.ofNullable(redisTemplate.hasKey(sign)).orElse(false);
if (exists) {
throw new MessagePromptException("重复提交");
}
signRedis.set(sign, 0, expireTime, TimeUnit.MILLISECONDS);
}
}