SpringCloud 필터

2310 단어 Java
게 이 트 웨 이에 필 터 를 설정 합 니 다.
서명 확인
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);

    }
}

좋은 웹페이지 즐겨찾기