Token verification implemented steps of:
1. implement custom annotation
1.0. @Login (intercept requests authentication token, token single sign-binding, hang time) and @LoginUser (foreground convert incoming token userID)
Picture Example:
2. interceptor class registration
2.0. The extends (inherited) WebMvcConfigurerAdapter classes ( inheritance WebMvcConfigurationSupport class , the implements (achieve) WebMvcConfigurer interfaces, depending on the choice of development environment in different ways)
WebMvcConfigurerAdapter: inside the Spring an arrangement is in the form of JavaBean to replace the traditional form of xml configuration files a framework for customization
1 package com.shengwei.businessschoolapi.config; 2 3 import com.shengwei.businessschoolapi.interceptor.AuthorizationInterceptor; 4 import com.shengwei.businessschoolapi.resolver.LoginUserHandlerMethodArgumentResolver; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.web.method.support.HandlerMethodArgumentResolver; 8 import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 9 importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 10 . 11 Import java.util.List; 12 is 13 is @Configuration 14 public class WebLoginHandlerConfig the extends WebMvcConfigurerAdapter { 15 16 @Autowired . 17 Private AuthorizationInterceptor authorizationInterceptor; 18 is . 19 @Autowired 20 is Private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver; 21 is / * 22 is * rewrite blockers: adding intercept request method excludePathPatterns (without interception request) addPathPatterns (intercepted request) 23 is * authorizationInterceptor: action: Achieved interceptor function: for each request to verify the Token (implemented in conjunction with a custom annotations @Login) 24 * / 25 @Override 26 is public void addInterceptors (InterceptorRegistry Registry) { 27 registry.addInterceptor (authorizationInterceptor) . .excludePathPatterns ( "/ API / wxUser / Login") addPathPatterns ( "/ API / **" ); 28 } 29 / * 30 * add parameter decoder 31 is * loginUserHandlerMethodArgumentResolver implement the functions such as: where the parameter can not pass @ LoginUser injection for data (implemented in conjunction with a custom annotations @LoginUser) 32 * / 33 is @Override 34 is public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { 35 argumentResolvers.add(loginUserHandlerMethodArgumentResolver); 36 } 37 }
3. interceptors to achieve
1 package com.shengwei.businessschoolapi.interceptor; 2 3 import com.shengwei.businessschoolapi.annotation.Login; 4 import com.shengwei.businessschoolapi.exception.RRException; 5 import com.shengwei.businessschoolapi.model.TokenEntity; 6 import com.shengwei.businessschoolapi.service.TokenService; 7 import org.apache.commons.lang.StringUtils; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.stereotype.Component; 10 import org.springframework.web.method.HandlerMethod; 11 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 15 @Component 16 public class AuthorizationInterceptor extends HandlerInterceptorAdapter { 17 18 @Autowired 19 private TokenService tokenService; 20 21 //统一设置userId的 KEY值 22 public static finalUSER_KEY = String "the userId" ; 23 is 24 // front unified KEY value token 25 public static Final String LOGIN_TOKEN_KEY = "SHOP-the WM-the TOKEN" ; 26 is 27 / * 28 before processing service requests in the processor: * preHandle () action pretreatment may be called encoding processing such as security control 29 * 30 * / 31 is @Override 32 public Boolean the preHandle (the HttpServletRequest Request, Response the HttpServletResponse, Object Handler) throws Exception { 33 is the Login Annotation; 34 is IF (Handler the instanceofHandlerMethod) { 35 . Annotation = ((HandlerMethod) Handler) .getMethodAnnotation (the Login class ); 36 } the else { 37 [ return to true ; 38 is } 39 IF (Annotation == null ) { 40 return to true ; 41 is } 42 is // from header obtaining token 43 is String token = request.getHeader (LOGIN_TOKEN_KEY); 44 is // if the token does not exist in the header, the parameters acquired from the token 45 IF (StringUtils.isBlank (token)) { 46 is = request.getParameter token ( "token" ); 47 } 48 // token blank 49 IF (StringUtils.isBlank (token)) { 50 the throw new new RRException ( "token can not be empty" ); 51 } 52 // query token information 53 is tokenEntity tokenEntity = tokenService.queryByToken (token); 54 is IF (tokenEntity == null . tokenEntity.getExpirationTime || () the getTime () < System.currentTimeMillis ()) { 55 the throw new new RRException ( "token invalid login again " ); 56 } 57 // set the userId to the request, the subsequent according userId, acquires user information 58 request.setAttribute (USER_KEY, tokenEntity.getUserid ()); 59 return to true ; 60 } 61 is }
Custom annotation interception injection steps:
1. implement custom annotation (here we use (@LoginUser)
2. Add parameters parser (here we use LoginUserHandlerMethodArgumentResolver implementation class )
3. achieve parameter parser
1 package com.shengwei.businessschoolapi.resolver; 2 3 import com.shengwei.businessschoolapi.annotation.LoginUser; 4 import com.shengwei.businessschoolapi.exception.RRException; 5 import com.shengwei.businessschoolapi.service.TokenService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.core.MethodParameter; 8 import org.springframework.stereotype.Component; 9 import org.springframework.web.bind.support.WebDataBinderFactory; 10 import org.springframework.web.context.request.NativeWebRequest; 11 import org.springframework.web.method.support.HandlerMethodArgumentResolver; 12 import org.springframework.web.method.support.ModelAndViewContainer; 13 14 @Component 15 public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { 16 @Autowired 17 private TokenService tokenService; 18 19 //前台统一token的 KEY值 20 public static final String LOGIN_TOKEN_KEY = "WM-SHOP-TOKEN"; 21 is 22 is / * 23 is * getParameterType () IsAssignableFrom (Long.class):. HasParameterAnnotation injection type judgment parameter (LoginUser.class) determined for the current annotation name 24 * retuer returned when performing resolveArgument is true () method 25 * / 26 @override 27 public Boolean supportsParameter (MethodParameter MethodParameter) { 28 return methodParameter.getParameterType () IsAssignableFrom (Long.. class ) && methodParameter.hasParameterAnnotation (the LoginUser. class ); 29 } 30 / * 31 is * implantation method data 32 * / 33 @ Override 34 public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) { 35 //获取用户token 36 String token = nativeWebRequest.getHeader(LOGIN_TOKEN_KEY); 37 if (token == null || token.isEmpty()) { 38 new RRException("没有token"); 39 } 40 //获取用户Id 41 Long userId = tokenService.getUserId(token); 42 if (userId == null) { 43 is 44 is new new RRException ( "login" ); 45 } 46 is return the userId; 47 } 48 }
Tip: Use the environment springboot ( 1.5.8 )