概述
前端请求接口时,经常用到token验证,并获取用户信息,通常做法是util包中创建一个UserTokenManager类,controller层的接口获取token,通过UserTokenManager.getUserByToken(token) 来获取用户信息。
本篇介绍另一种方法,通过HandlerMethodArgumentResolver和注解,统一获取当前登录用户
在SpringBoot中使用HandlerMethodArgumentResolver
- 创建util包,并创建UserTokenManager.java 用户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;
}
}
- 创建注解LoginUser
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}
- 创建annotation包,并创建LoginUserHandlerMethodArgumentResolver自定义方法参数解析器,并继承HandlerMethodArgumentResolver
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 {
// return new Integer(1);
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());
}
}
- OK,做好以上这些准备工作,就可以在接口里使用@LoginUser注解了,如下
@RestController
@RequestMapping("/wx/user")
@Validated
public class WxUserController {
private final Log logger = LogFactory.getLog(WxUserController.class);
@Autowired
private LitemallOrderService orderService;
/**
* 用户个人页面数据
* <p>
* 目前是用户订单统计信息
*
* @param userId 用户ID
* @return 用户个人页面数据
*/
@GetMapping("index")
public Object list(@LoginUser Integer userId) {
//通过@LoginUser获取userId,判断用户是否登录
if (userId == null) {
return ResponseUtil.unlogin();
}
Map<Object, Object> data = new HashMap<Object, Object>();
//TODO 业务数据data填充
return ResponseUtil.ok(data);
}
}
总结
好了,以上就是SpringBoot中,通过HandlerMethodArgumentResolver来统一获取当前登录用户的方法。