当前位置: 首页 > news >正文

Spring项目使用JWT进行后端鉴权

Spring项目使用JWT进行后端鉴权

  1. 添加需要使用的新依赖项
        <dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.10.3</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.24</version></dependency>
  1. 添加访问路径前缀配置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.addPathPrefix("/api",clazz ->clazz.isAnnotationPresent(RestController.class));}
}
  1. 将原理@Controller类中的@Controller注解替换为@RestController;
  2. JWT鉴权原理如下
    https://blog.51cto.com/u_9806927/12294431
  3. 在项目中添加JWT工具
package com.example.demo.common;import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demo.service.UserService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;import java.util.Date;@Component
public class JwtTokenUtils {private static UserService staticUserService;@Resourceprivate UserService userService;@PostConstructpublic void setUserService() {userService = staticUserService;}public static String genToken(String account, String password) {return JWT.create().withAudience(account)//将account保存在载荷中.withExpiresAt(DateUtil.offsetHour(new Date(), 2))//设置token有效时间.sign(Algorithm.HMAC256(password));//以password为密钥进行加密}}
  1. 重构User类,重写登录接口,当用户登录成功后,将token一起返回给前端;
  2. 在项目中添加拦截器,用于校验JWTtoken的正确性
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.JWTVerificationException;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;@Component
public class JwtInterceptor implements HandlerInterceptor {private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);@Resourceprivate UserService userService;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {String token = request.getHeader("token");if(StrUtil.isBlank(token)){token = request.getParameter("token");}if(StrUtil.isBlank(token)){throw new Exception("登录状态异常,请重新登录");}String account;User user = null;try{account = JWT.decode(token).getAudience().get(0);user = userService.findUserByAccount(account);}catch (Exception e){log.error("无效tonken,token:" + token);}if(user == null){throw new Exception("用户不存在,请重新登录");}try{JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();jwtVerifier.verify(token);}catch (JWTVerificationException e){throw new Exception("token验证失败,请重新登录");}return true;}
}
  1. 在拦截器配置到对应的接口上面
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Resourceprivate JwtInterceptor jwtInterceptor;@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.addPathPrefix("/api",clazz ->clazz.isAnnotationPresent(RestController.class));}@Overridepublic void addInterceptors(InterceptorRegistry registry){registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**").excludePathPatterns("/api/user/login").excludePathPatterns("/api/user/register");}
}

相关文章:

  • 让数据优雅落地:用 serde::Deserialize 玩转结构体实体
  • Prompt
  • Go 1.24 is released(翻译)
  • 【leetcode】最长公共子路径问题
  • TypeScript概述
  • 2025年特种设备作业人员考试题库及答案(流动式起重机Q2)
  • 2.2.2goweb内置的 HTTP 处理程序2
  • gem5教程 第七章 如何在 gem 5 中运行我自己的程序
  • 深入理解网络原理:TCP协议详解
  • 测试用例介绍
  • 微分与积分(前言)
  • 【CodeSprint】第二章-2.1 简单模拟
  • C++ STL编程 vector的插入、删除、扩容机制、随机访问和内存交换
  • 智能Python开发工具PyCharm v2025.1——AI层级功能重磅升级
  • 【学习笔记】机器学习(Machine Learning) | 第六周|过拟合问题
  • 机器学习day3 - KNN的api调用
  • vue报错:Loading chunk * failed,vue-router懒加载出错问题。
  • 马克·雷伯特:用算法让机器人飞奔的人
  • 十一、引用与拷贝函数(References the Copy-Constructor)
  • 节流和防抖
  • 四川落马厅官周海琦受审,1000余人接受警示教育
  • 大家聊中国式现代化|周冯琦:转角见美,让“绿意”触手可及
  • 湖南小伙“朱雀玄武敕令”提交申请改名为“朱咸宁”
  • 经济日报金观平:统筹国内经济工作和国际经贸斗争
  • “十四五”以来少数民族发展资金累计下达边疆省区252亿元
  • 理想汽车副总裁刘杰:不要被竞争牵着鼻子走,也不迷信护城河