SpringBoot集成JWT实现token验证使用

 大佬JWT教程https://blog.csdn.net/Top_L398/article/details/109361680

参考的大佬的JWT集成https://blog.csdn.net/gjtao1130/article/details/111658060

目录结构

请结合前文使用 (什么自定义异常类啥的都在前面

pom依赖引入

<!-- JWT -->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.10.3</version>
</dependency>

用于生成token的类(TokenUtils.java)

package com.example.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.service.UserService;
import javax.annotation.Resource;
import java.util.Date;

public class TokenUtils {
    /**
     * 生成token
     *
     * @return
     */

    /**
     * 过期时间5分钟
     */
    //private static final long EXPIRE_TIME = 5 * 60 * 1000;
        
    // //签名私钥
    //private String KEY="chiix";
    // //签名的失效时间
    //private Long ttl=360000L;

    public static String genToken(String userId, String sign) {
        //Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        return JWT.create().withAudience(userId) // 将 userid 保存到 token 里面,作为载荷
                //.withClaim("yourself",sth)//payload  //自定义载荷内容声明                
                //.withExpiresAt(date) //五分钟后token过期
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }

}

用于拦截token的拦截器(JwtInterceptor.java)

package com.example.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.Exception.ServiceException;
import com.example.common.Constants;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求头中的token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(Constants.CODE_401, "无token,请重新登录");
        }
        // 获取 token 中的 userid 载荷验证
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            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); // 验证token
        }
        catch (SignatureVerificationException e) {
            throw new ServiceException(Constants.CODE_401, "token无效签名,请重新登录");
        } catch (TokenExpiredException e) {
            throw new ServiceException(Constants.CODE_401, "token过期,请重新登录");
        } catch (AlgorithmMismatchException e) {
            throw new ServiceException(Constants.CODE_401, "token算法不一致,请重新登录");
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录");
        }
        return true;
    }
}

拦截器的注册(InterceptorConfig.java)

package com.example.config;

import com.example.config.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                .addPathPatterns("/**")  // 拦截所有请求,通过判断token是否合法来决定是否需要登录
                .excludePathPatterns("/login", "/register");//不拦截的请求
    }
    //注入到bean工厂中,交给spring管理
    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }
}

修改login方法(登入时,将生成token返回前端)

    //登录
    @Override
    public UserVO login(UserDTO userDTO) {
        //DTO前端返回后端的数据接受类
        //VO后端返回前端的数据类
        User one = getUserInfo(userDTO);
        UserVO VO = new UserVO();
        if (one != null) {
            BeanUtil.copyProperties(one, VO, true);

            //设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            VO.setToken(token);

            return VO;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }

    }

 前端的axios请求修改

import axios from 'axios'
import ElementUI from 'element-ui'
const request = axios.create({
    baseURL: 'http://localhost:9002/back',
    timeout: 5000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

    let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    if (user) {
        config.headers['token'] = user.token;  // 设置请求头
    }
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        // 当权限验证不通过的时候给出提示
        if (res.code === '401') {
            ElementUI.Message({
                message: res.msg,
                type: 'error'
            });
        }
        return res;
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)


export default request

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值