当前位置:网站首页>JJWT工具类
JJWT工具类
2022-08-02 03:21:00 【Tom没Cat】
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
JJWT 工具类
package com.example.utils.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
/** * @author zpc * @version 1.0 * @date 2022/2/19 13:56 */
@Component
@ConfigurationProperties(prefix = "jwt.config")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtUtil {
private String key;
private long ttl;
/** * 生成 JWT * @param id * @param subject * @param roles 角色 * @return */
public String createJWT(String id, String subject, String roles) {
long nowMillis = System.currentTimeMillis();
Date nowDate = new Date(nowMillis);
HashMap<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT");
JwtBuilder builder = Jwts.builder()
.setHeaderParams(map)
// 设置 id
.setId(id)
// 设置用户名
.setSubject(subject)
// 设置 jwt 签发时间
.setIssuedAt(nowDate)
// 设置签名使用的签名算法和签名使用的密钥
.signWith(SignatureAlgorithm.HS256, key)
.claim("roles", roles);
if (ttl > 0) {
builder.setExpiration(new Date(nowMillis + ttl));
}
return builder.compact();
}
/** * 解析 JWT * @param jwtStr * @return */
public Claims parseJWT(String jwtStr) {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwtStr)
.getBody();
}
}
application.yml 配置
jwt:
config:
ttl: 设置过期时间
key: 设置签名使用的密钥
边栏推荐
猜你喜欢

Daily practice------There are n integers, so that the previous numbers are moved back m positions in order, and the last m numbers become the first m numbers

MongoDB文档存储

AntV X6制作画板工具(图形,线段,图片上传)

Using WebShell to get Shell Skills

CV-Model【4】:MobileNet v3

磷脂-聚乙二醇-叠氮,DSPE-PEG-Azide,DSPE-PEG-N3,MW:5000

磷脂-聚乙二醇-靶向新生血管靶向肽APRPG,DSPE-PEG-APRPG

线性代数学习笔记3-1:矩阵与线性变换、常见矩阵(逆矩阵、伴随矩阵、正交矩阵等)

关于跨域问题

Webshell upload method
随机推荐
MySQL删除表数据 MySQL清空表命令 3种方法
LeetCode:1161. 最大层内元素和【BFS层序遍历】
Redis安装,基本命令,持久化方式,集群
「PHP基础知识」PHP中对象的使用
STM32——LCD—TFTLCD原理与配置介绍
STL entry basics map and set containers
5. Hezhou Air32F103_LCD_key
Redis笔记进阶篇:万字长文-整理Redis,各种知识点,建议收藏
赶紧进来!!!教你用C语言写三子棋小游戏
OD-Model【4】:SSD
关于#sql#的问题:该怎么写sql语句,
API 低代码开发:接口大师,一套开发、管理和提供接口的产品框架
rem适配
@Accessors 注解详解
(转帖)HashCode总结(2)
MySQL中JOIN的用法
科研试剂DMPE-PEG-Mal 二肉豆蔻酰磷脂酰乙醇胺-聚乙二醇-马来酰亚胺
@ApiModel 和 @ApiModelProperty
Scaffolding installation
Week 7 Review