SpringCloud 过滤器

在网关中配置过滤器

验证签名

package com.kps.zuul.filter;


import com.kps.common.BodyReaderHttpServletRequestWrapper;
import com.kps.common.encrypt.MD5;
import com.kps.common.exception.ErrorTokenException;
import com.kps.common.utils.NetUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@SuppressWarnings("all")
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(filterName = "ValidAppSign", urlPatterns = {"/app/api/*"})
public class ValidAppSign extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(ValidToken.class);
public final static String ERROR_TOKEN = "Sign is invalid";

@Value("${isDebug}")
private boolean isDebug;
@Value("${appSign}")
private String appSign;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
//获取 body 中post过来的数据
String contentType = request.getContentType();
if (StringUtils.isNotBlank(contentType) && contentType.indexOf(MediaType.APPLICATION_JSON.toString()) >= 0) {
request = new BodyReaderHttpServletRequestWrapper(request);
}
String data = null;
try {
data = NetUtil.getBodyString(request);
} catch (Exception e) {
e.printStackTrace();
}
//获取 url 中的数据
String sign = request.getParameter("sign");
String signMD5= MD5.getSign(data,appSign);
if(!sign.equals(signMD5)){
throw new ErrorTokenException(ERROR_TOKEN);
}


filterChain.doFilter(request, response);

}
}

 


 

posted @ 2019-01-16 16:52  正怒月神  阅读(1279)  评论(0编辑  收藏  举报