本文共 2401 字,大约阅读时间需要 8 分钟。
importcom.auth0.jwt.JWT;importcom.auth0.jwt.JWTVerifier;importcom.auth0.jwt.algorithms.Algorithm;importcom.auth0.jwt.exceptions.JWTDecodeException;importcom.auth0.jwt.exceptions.JWTVerificationException;importcom.my_springboot.rbac.pojo.Admin;importcom.my_springboot.rbac.service.IAdminService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.method.HandlerMethod;importorg.springframework.web.servlet.HandlerInterceptor;importorg.springframework.web.servlet.ModelAndView;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.lang.reflect.Method;/*** 拦截器去获取token并验证token*/
public class AuthenticationInterceptor implementsHandlerInterceptor {
@AutowiredprivateIAdminService adminService;
@Overridepublic booleanpreHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object object) {
String token= httpServletRequest.getHeader ("token");//从 http 请求头中取出 token//如果不是映射到方法直接通过
if (!(object instanceofHandlerMethod)) {return true;
}
HandlerMethod handlerMethod=(HandlerMethod) object;
Method method=handlerMethod.getMethod ();//检查是否有@passtoken注解,有则跳过认证
if (method.isAnnotationPresent (PassToken.class)) {
PassToken passToken= method.getAnnotation (PassToken.class);if(passToken.required ()) {return true;
}
}//检查有没有需要用户权限的注解
if (method.isAnnotationPresent (UserLoginToken.class)) {
UserLoginToken userLoginToken= method.getAnnotation (UserLoginToken.class);if(userLoginToken.required ()) {//执行认证
if (token == null) {throw new RuntimeException ("无token");
}//获取 token 中的 user id
String adminId;try{
adminId= JWT.decode (token).getAudience ().get (0);
}catch(JWTDecodeException j) {throw new RuntimeException ("401");
}
Admin admin=adminService.getById (adminId);if (admin == null) {throw new RuntimeException ("用户不存在");
}//验证 token
JWTVerifier jwtVerifier =JWT.require (Algorithm.HMAC256 (admin.getPassword ())).build ();try{
jwtVerifier.verify (token);
}catch(JWTVerificationException e) {throw new RuntimeException ("401");
}return true;
}
}return true;
}
@Overridepublic voidpostHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)throwsException { }
@Overridepublic voidafterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)throwsException { }
}
转载地址:http://ajima.baihongyu.com/