0
点赞
收藏
分享

微信扫一扫

spring 拦截器和自定义注解进行登录拦截

_阿瑶 2022-05-11 阅读 62

项目地址: https://github.com/hyrijk/spring-boot-blog


spring 拦截器和自定义注解进行登录拦截_请求头

spring 拦截器和自定义注解进行登录拦截_请求头_02

public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;


public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// 如果不是映射到方法直接通过
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();


// 判断接口是否需要登录
LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
// 有 @LoginRequired 注解,需要认证
if (methodAnnotation != null) {
// 执行认证
String token = request.getHeader("token"); // 从 http 请求头中取出 token
if (token == null) {
throw new RuntimeException("无token,请重新登录");
}
int userId;
try {
userId = Integer.parseInt(JWT.decode(token).getAudience().get(0)); // 获取 token 中的 user id
} catch (JWTDecodeException e) {
throw new RuntimeException("token无效,请重新登录");
}
User user = userService.findById(userId);
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
}
// 验证 token
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
verifier.verify(token);
} catch (JWTVerificationException e) {
throw new RuntimeException("token无效,请重新登录");
}
} catch (UnsupportedEncodingException ignore) {}
request.setAttribute("currentUser", user);
return true;
}
return true;
}

spring 拦截器和自定义注解进行登录拦截_github_03

spring 拦截器和自定义注解进行登录拦截_请求头_04

spring 拦截器和自定义注解进行登录拦截_请求头_05

spring 拦截器和自定义注解进行登录拦截_spring_06


举报

相关推荐

0 条评论