java token认证机制,从零开始的SpringBoot项目 ( 七 ) 实现基于Token的用户身份验证...

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 { }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值