• SpringBoot集成Jwt


     

    1.jwt是什么?

    jwt全称jsonwebtoken。主要应用与登录授权,信息交换。

    结构:标头(header)、载荷(Payload)、签名(Signature)。

    2. 如何生成token?

    首先配置依赖

    1. com.auth0
    2. java-jwt
    3. 3.10.3

    我是在utils中编写TokenUtils工具类。

    1. public class TokenUtils {
    2. public static String getToken(String userId,String sign){
    3. return JWT.create().withAudience(userId).withExpiresAt(DateUtil.offsetHour(new Date(),2)).sign(Algorithm.HMAC256(sign));
    4. }
    5. }

    在登录时,调用TokenUtils.getToken(userid,sign)拿到token。

    userDTO.setToken(token);

    赋值给DTO返给前端。

    3. 如何验证token,实现授权。

    创建JwtInterceptor类,实现接口HandlerInterceptor(拦截器),重写preHandle方法。

    1. public class JwtInterceptor implements HandlerInterceptor {
    2. @Resource
    3. private IUserService userService;
    4. @Override
    5. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    6. String token = request.getHeader("token");
    7. // 如果不是i映射到方法直接通过
    8. if(!(handler instanceof HandlerMethod)){
    9. return false;
    10. }
    11. // 执行认证
    12. if(StrUtil.isBlank(token)){
    13. throw new ServiceException(Constants.CODE_401,"无token,请重新登录");
    14. }
    15. // 获取token中的userid
    16. String userId;
    17. try{
    18. userId = JWT.decode(token).getAudience().get(0);
    19. }catch (Exception e){
    20. throw new ServiceException(Constants.CODE_401,"token验证失败");
    21. }
    22. // 根据token中的userid查询数据库
    23. User user = userService.getById(userId);
    24. if(user== null){
    25. throw new ServiceException(Constants.CODE_401,"用户不存在,请重新登录");
    26. }
    27. // 验证token
    28. JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
    29. try{
    30. jwtVerifier.verify(token);
    31. }catch (JWTVerificationException e){
    32. throw new ServiceException(Constants.CODE_401,"token验证失败,请重新登录");
    33. }
    34. return true;
    35. }
    36. }

    创建配置类InterceptorConfig,这里说明一下

    @Configuration启动容器+@Bean注册Bean,@Bean下管理bean的生命周期

    @Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的,作用为:注册bean对象

    1. @Configuration
    2. public class InterceptorConfig implements WebMvcConfigurer {
    3. @Override
    4. public void addInterceptors(InterceptorRegistry registry) {
    5. registry.addInterceptor(jwtInterceptor())
    6. .addPathPatterns("/**")
    7. .excludePathPatterns("/user/login","/user/register","/user/export","/user/import");
    8. }
    9. @Bean
    10. public JwtInterceptor jwtInterceptor(){
    11. return new JwtInterceptor();
    12. }
    13. }

     

  • 相关阅读:
    vue引入element-plus显示找不到import ‘element-plus/dist/index.css‘
    [L437] 前缀和
    深入理解synchronized关键字
    元宇宙:打破虚拟与现实的边际
    LeetCode-究极刷题【合集】
    代码随想录算法训练营第三十天| LeetCode332. 重新安排行程、LeetCode51. N 皇后、LeetCode37. 解数独
    【智能家居入门3】(MQTT服务器、MQTT协议、微信小程序、STM32)
    【Python基础】2万字-详解Python基础函数,包教包会
    学习MySQL-第六章
    都2202年了,不会有人还不会发布npm包吧
  • 原文地址:https://blog.csdn.net/m0_53273062/article/details/133930708