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

授权与认证之jwt(一)创建Jwt工具类

JWT的Token要经过加密才能返回给客户端,包括客户端上传的Tokn,后端项目需要验证核
实。于是我们需要一个WT工具类,用来加密Token和验证Token的有效性。

一、导入依赖

        <dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.10.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.11</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.13</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>

二、定义密钥和过期时间

在application文件中加入,建议大家把密钥和过期时间定义到Spring Boot配置文件中,然后再值注入到javaBean中,这样维护起来比较方便。

emos:jwt:#密钥secret: abc123456#令牌过期时间(天)expire: 5#令牌缓存时间(天)cache-expire: 10

三、创建jwt工具类

@Component
@Slf4j
public class JwtUtil {@Value("${emos.jwt.secret}")  //读取的就是application文件中的数值private String secret;@Value("${emos.jwt.expire}")private int expire;//创建令牌private String createToken(int userId) {//根据expire算下过期时间在什么时候DateTime date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, 5);//生成密钥Algorithm algorithm= Algorithm.HMAC256(secret);//创建内部类绑定userid,密钥和过期时间JWTCreator.Builder builder= JWT.create();builder.withClaim("userId", userId);builder.withExpiresAt(date);//生成的令牌String token = builder.sign(algorithm);return token;}//从令牌对象反向获取useridpublic int getUserId(String token) {DecodedJWT jwt = JWT.decode(token);Integer userId = jwt.getClaim("userId").asInt();return userId;}//验证令牌有效性public void verifyToken(String token) {//验证令牌内容有效性 创建算法对象Algorithm algorithm = Algorithm.HMAC256(token);//创建验证对象JWTVerifier build = JWT.require(algorithm).build();//验证token是否有问题build.verify(token);}
}

http://www.lryc.cn/news/545491.html

相关文章:

  • Kubernetes Service服务发现dns之CoreDNS
  • Spring Boot 测试:单元、集成与契约测试全解析
  • 用友NC系列漏洞检测利用工具
  • PostgreSQL 创建表格
  • 一周一个Unity小游戏2D反弹球游戏 - 球的死区及球重生
  • 本地部署 DeepSeek:从 Ollama 配置到 Spring Boot 集成
  • vue3:三项目增加404页面
  • MCAL(Microcontroller Abstraction Layer)介绍
  • 爬虫:PhantomJS的详细使用和实战案例
  • 目标检测——数据处理
  • 深度学习工程师的技术图谱和学习路径
  • Qt 文件操作+多线程+网络
  • 如何使用ArcGIS Pro制作横向图例:详细步骤与实践指南
  • Kotlin 嵌套类和内部类
  • 蓝蝶(BlueStacks)模拟器Root、Magisk、LSPosed及Shamiko框架安装与过应用检测指南
  • OpenCV计算摄影学(6)高动态范围成像(HDR imaging)
  • [ComfyUI][AI生图]如何在Comfyui中安装插件管理器
  • 初探Ollama与deepseek
  • Linux top 常用参数记录
  • CCF-CSP认证 202104-1灰度直方图
  • 怎么下载安装yarn
  • Vulhub靶机 AppWeb认证绕过漏洞(CVE-2018-8715)(渗透测试详解)
  • CSS 系列之:grid 布局
  • DeepSeek MLA(Multi-Head Latent Attention)算法浅析
  • 【计算机网络入门】初学计算机网络(七)
  • Conda 环境搭建实战:从基础到进阶
  • 大数据-236 离线数仓 - 会员活跃度 WDS 与 ADS 导出到 MySQL 与 广告业务 需求分析
  • fps项目总结:关于攻击与受击
  • coze生成的工作流,发布后,利用cmd命令行执行。可以定时发日报,周报等。让他总结你飞书里面的表格。都可以
  • Windows 10 远程桌面连接使用指南