HandlerMethodArgumentResolver 和 jwt 实现权限认证

token管理类

public class UserTokenManager {
     //生成TOKEN
    public static String generateToken(Integer id) {
        JwtHelper jwtHelper = new JwtHelper();
        return jwtHelper.createToken(id);
    } 

    //根据TOKEN获取用户ID
    public static Integer getUserId(String token) {
        JwtHelper jwtHelper = new JwtHelper();
        Integer userId = jwtHelper.verifyTokenAndGetUserId(token);
        if(userId == null || userId == 0){
            return null;
        }
        return userId;
    }
}

创建请求拦截注解,处理登陆权限

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {

}

拦截处理方法

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public static final String LOGIN_TOKEN_KEY = "X-Authentication-Token";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            return null;
        }

        return UserTokenManager.getUserId(token);
    }
}

创建WxWebMvcConfiguration配置类,并继承WebMvcConfigurer

@Configuration
public class WxWebMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new LoginUserHandlerMethodArgumentResolver());
    }
}

然后就可以把校验注解加载接口的参数中了

 @GetMapping("test")
    public Object list(@LoginUser Integer userId) {
      
        return “成功”;
    }

 

HandlerMethodArgumentResolver 和 jwt 实现权限认证

上一篇:Wine卸载


下一篇:给新建的Cocos2d-x 3.X的Win32工程添加CocoStudio库