jwt全称jsonwebtoken。主要应用与登录授权,信息交换。
结构:标头(header)、载荷(Payload)、签名(Signature)。
首先配置依赖
-
com.auth0 -
java-jwt -
3.10.3 -
我是在utils中编写TokenUtils工具类。
- public class TokenUtils {
- public static String getToken(String userId,String sign){
- return JWT.create().withAudience(userId).withExpiresAt(DateUtil.offsetHour(new Date(),2)).sign(Algorithm.HMAC256(sign));
- }
- }
在登录时,调用TokenUtils.getToken(userid,sign)拿到token。
userDTO.setToken(token);
赋值给DTO返给前端。
创建JwtInterceptor类,实现接口HandlerInterceptor(拦截器),重写preHandle方法。
- public class JwtInterceptor implements HandlerInterceptor {
- @Resource
- private IUserService userService;
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- String token = request.getHeader("token");
- // 如果不是i映射到方法直接通过
- if(!(handler instanceof HandlerMethod)){
- return false;
- }
- // 执行认证
- if(StrUtil.isBlank(token)){
- throw new ServiceException(Constants.CODE_401,"无token,请重新登录");
- }
- // 获取token中的userid
- String userId;
- try{
- userId = JWT.decode(token).getAudience().get(0);
- }catch (Exception e){
- throw new ServiceException(Constants.CODE_401,"token验证失败");
- }
- // 根据token中的userid查询数据库
- User user = userService.getById(userId);
- if(user== null){
- throw new ServiceException(Constants.CODE_401,"用户不存在,请重新登录");
- }
-
- // 验证token
- JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
- try{
- jwtVerifier.verify(token);
- }catch (JWTVerificationException e){
- throw new ServiceException(Constants.CODE_401,"token验证失败,请重新登录");
- }
-
- return true;
- }
- }
创建配置类InterceptorConfig,这里说明一下
@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的,作用为:注册bean对象
- @Configuration
- public class InterceptorConfig implements WebMvcConfigurer {
-
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(jwtInterceptor())
- .addPathPatterns("/**")
- .excludePathPatterns("/user/login","/user/register","/user/export","/user/import");
- }
- @Bean
- public JwtInterceptor jwtInterceptor(){
- return new JwtInterceptor();
- }
- }