Springboot background intercept parameters, decoding or interface interception

A usage scenarios:

1. The procedure of the front end interface calls, some interface data to be encrypted is transmitted: such as a password, etc., after the front end of the rear end of the interface must be encoded to be decoded, each interface Solutions done once a decoding operation, which is a very complicated matter

2. The invocation interface, you need to transfer a token each call, how do we go about interfaces to intercept

So this paper to talk about their own implementations of global decoded at work:

The front end of the front reference coding method essay: https://www.cnblogs.com/KdeS/p/12073331.html

 

 II. Definition Filter or a OncePerRequestFilter

 OncePerRequestFilter: (in the spring, filter by default inherit OncePerRequestFilter) As the name suggests, it is possible to ensure that only one request by a filter, and the need to repeat the execution. We believe that the common sense, a request already filter only once, why should thus particularly limited and it is often our common sense and practical implementation is not the real thing, through access to some data, this method is different for compatibility the web container, the container that is not all we expect are the only one at a time, different versions of servlet, the implementation process is different, therefore, to be compatible with a variety of different operating environments and versions, the default filter is a relatively safe inherit OncePerRequestFilter s Choice. request.parameterIn, but we all know that request.parameterdata can only be read, can not write, how to solve it?

 Here will be the introduction of a class  javax.servlet.http.HttpServletRequestWrapper, it is an extension of the common interface, that is, will requestdo a package, we need to inherit and override this method.

 

Code portion below 2.1
com.grand.p1upgrade.filter Package; 

Import the java.util.HashMap; 
Import a java.util.Map; 
Import the javax.servlet.http.HttpServletRequest; 
Import javax.servlet.http.HttpServletRequestWrapper; 

public  class MyHttpServletRequestWrapper the extends the HttpServletRequestWrapper { 

    // with storing request parameter 
    Private the map <String, String []> the params = new new the HashMap <String, String []> (); 
         
    public MyHttpServletRequestWrapper (the HttpServletRequest request) { 
        Super (request); 
        // add to our own request parameter map among 
        the this . the params .putAll (request.getParameterMap ()); 
    }
    public void setParameters(Map<String, Object> extraParams) {
        for (Map.Entry<String, Object> entry : extraParams.entrySet()) {
            setParameter(entry.getKey(), entry.getValue());
        }
    }
    /**
     * 添加参数到map中
     * @param name 
     * @param value
     */
    public void setParameter(String name, Object value) {
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if(the instanceof String value) {
                 the params .put (name, new new String [] {(String) value}); 
            } the else {
                 the params .put (name, new new String [] {String.valueOf (value)}); 
            } 
        } 
    } 
    
    / * * 
     * rewriting getParameter, obtain parameters representing the current class Map 
     * @param name 
     * @return 
     * / 
    @Override 
    public String the getParameter (String name) { 
        String [] values = the params . GET (name);
         IF ( == values nullValues.length == || 0 ) {
             return  null ; 
        } 
        return values [ 0 ]; 
    } 

    / * * 
     * getParameterValues rewriting method, the current value from the map class 
     * @param name 
     * @return 
     * / 
    @Override 
    public String [] the getParameterValues (String name) {
         return  the params . GET (name); 
    } 
}
 
2.2 Inheritance OncePerRequestFilter coverage doFilterInternal password decoding
com.grand.p1upgrade.filter Package; 

Import java.io.IOException; 
Import java.util.Base64; 
Import a javax.servlet.FilterChain; 
Import javax.servlet.ServletException; 
Import the javax.servlet.http.HttpServletRequest; 
Import the javax.servlet .http.HttpServletResponse; 
Import org.springframework.stereotype.Component; 
Import org.springframework.web.filter.OncePerRequestFilter; 

/ * * 
 * parameter filtering, intercepts all requests whether there pwd request interface parameters, it is decrypted and the parameters placed in request.parameter 
 * 
 * @author Sanli 
 * the Created by [email protected]/SanLi ON 2018/1/28 
 * / 
// @Component 
public  class RequestParameterFilter the extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String pwd=request.getParameter("pwd");
        if(pwd!=null) {
            pwd= new String(Base64.getDecoder().decode(pwd), "UTF-8");
            MyHttpServletRequestWrapper wrapper = new MyHttpServletRequestWrapper(request);
            wrapper.setParameter("pwd", pwd);
 / * * 
 * is a filter chain 1. Usually, web.xml configuration inside a few have several. One by one together 
 * Request -> Filter1 to -> filter2 -> filter3 -> ... -..> Resource Request 
 * 
 * 2.chain.doFilter forwards the request to the next filter chain a filter, if there is no filter that you resource request 
 * / 
            the FilterChain.doFilter (warpper, Response); 
        } 
        return ; 
    } 

}
2.2 Inheritance Filter to decode password
package com.grand.p1upgrade.filter;

import java.io.IOException;
import java.util.Base64;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import lombok.extern.java.Log;

/**
 * Filter all requests include static resources, if the request contains a cookie or token requests for static resources, the release request, otherwise go to the login page 
 * / 
@Log 
@Component 
public  class TokenFilter the implements the Filter { 

    @Override 
    public  void the init (FilterConfig FilterConfig) throws ServletException {} 

    @Override 
    public  void the doFilter (the servletRequest servletRequest, the ServletResponse ServletResponse, 
            the FilterChain catena alberghiera) throws IOException, ServletException { 
        MyHttpServletRequestWrapper warpper = null ; 
        String token = null ; 
        the HttpServletRequest Request =(The HttpServletRequest) servletRequest; 
        the HttpServletResponse Response = (the HttpServletResponse) ServletResponse; 
        String URI = Request.getRequestURI ();
        // parameter filter, intercepts all requests whether there pwd request interface parameters, there is the decryption, into request parameters and .parameter the 
        String pwd = request.getParameter ( " pwd " );         
        warpper = new new MyHttpServletRequestWrapper (Request);
         IF (! pwd = null ) { 
            pwd = new new . String (Base64.getDecoder () decode (pwd), " UTF 8 " );
            wrapper.setParameter ( " pwd " , pwd); 
        } 
      
        IF (uri.contains ( " / Login " )) || uri.contains ( " / static " )) {
            // through, does not intercept 
            chain.doFilter (wrapper, response ); 
        } the else {
             // intercepts the request, determines whether there is a cookie token, not jump to the login page with the release 
            cookies [] = cookies request.getCookies ();
             iF ! (cookies = null ) {
                 for (cookies the cookie: Cookies) {
                     IF ( "token " .equals (the Cookie.getName ())) {
                         // the front end of the passed token consists of two parts: Key, value 
                        token = cookie.getValue (); 
                    } 

                } 
            } 
            // token has a value, and comprising," _ ", on by 
            IF (StringUtils.isNotEmpty (token) && token.contains ( " _ " )) { 
                the chain.doFilter (warpper, Response); 
            } the else { 
                response.setStatus ( 401 ); // needs permission 
            } 
        } 
    } 

    @Override 
    public void destroy() {}

}

 

 

to sum up:

OncePerRequestFilter inheritance or succession Filter in the process I use to achieve the same effect we want.

Guess you like

Origin www.cnblogs.com/KdeS/p/12101672.html