How to convert gracefully into Token parameter userId

In a real project, we tend to be issued a tokencertificate to the front end, the front end by a request parameter or request headers in every request will tokenbe passed to the back-end verification. Rear end is obtained token, will be verified after tokenconverted into the parameters of the actual needs, for example userId.

In SrpingBootthe project, since no request parameter userIdthis parameter, so we can not obtain the reference shape by a process userId, we need HttpServletWrapperto be tokenconverted to a userIdparameter.

1, inheritance HttpServletWrapper class and override the method getParameterValues

Note: do not use real here token, but with an mapanalog tokenstorage tokenof 123and 456valid token, corresponding userId = 1anduserId = 2

/**
* Token请求包装类,将token字段转换成userId字段
* @author yan
* @date 2019年10月17日
*/
public class TokenHttpServletWrapper extends HttpServletRequestWrapper{
   private Logger logger = LoggerFactory.getLogger(getClass());
   
   private Map<String,Integer> tokenMap;    //模拟token
   
   public TokenHttpServletWrapper(HttpServletRequest request) {
   	super(request);
   	tokenMap = new HashMap<>() {
   		{
   			put("123", 1);
   			put("456", 2);
   		}
   	};
   }


   @Override
   public String[] getParameterValues(String name) {
   	//如果请求参数不是userId,则跳过
   	if(!"userId".equals(name)) {
   		return super.getParameterValues(name);
   	}
   	//检验token,转换成相应的userId
   	String token = super.getParameter("token");
   	if(token == null) {
   		return null;
   	}
   	logger.debug("token:" + token);
   	Integer userId = tokenMap.get(token);
   	logger.debug("userId:" + userId);
   	return userId == null ? null : new String[] {String.valueOf(userId)};
   }
}
复制代码

2, the filter is defined, it determines whether tokenthe parameter or tokenparameters are valid

AbstractFilterIs a custom filter abstract class, mainly for adding negative path functions, consistent with other uses filters

public class TokenFilter extends AbstractFilter{

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String token = request.getParameter("token");
		if(!"123".equals(token) && !"456".equals(token)) {
			CodeResult codeResult = new CodeResult(CodeEnum.UNAUTHORIZED, null);
			response.setContentType("text/json;charset=utf-8");
			response.getWriter().write(BeanUtil.beanToJson(codeResult));
			return;
		}
		chain.doFilter(new TokenHttpServletWrapper(request), response);
	}
	
}
复制代码

3, the filter configuration

@Configuration
public class TokenFilterConfig {
	@Bean
	public FilterRegistrationBean<Filter> securityFilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		Filter filter = new TokenFilter();
		registration.setFilter(filter);
        registration.addUrlPatterns("/*");
        registration.setName("tokenFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registration;
	}
}
复制代码

4, in the Controllermethod of use userIdas a parameter

5, the interface requests access to the

  1. When no tokenparameter or tokenparameter is invalid, returns unauthorized information

  1. When the tokenparameter is valid, to obtain the correspondinguserId

Guess you like

Origin juejin.im/post/5db7b4fe51882540fd168c40