当前位置:网站首页>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: 设置签名使用的密钥
边栏推荐
猜你喜欢
@DateTimeFormat注解
小程序(开发必备常识)1
MySQL中JOIN的用法
CV-Model [4]: MobileNet v3
Keil development environment installation tutorial
DSPE-PEG-PDP,DSPE-PEG-OPSS,磷脂-聚乙二醇-巯基吡啶供应,MW:5000
ModuleNotFoundError: No module named ‘openpyxl‘
@Autowired与@Resource区别
day11--shell脚本
活体检测 Adaptive Normalized Representation Learning for GeneralizableFace Anti-Spoofing 阅读笔记
随机推荐
rem adaptation
DSPE-PEG-Silane,DSPE-PEG-SIL,磷脂-聚乙二醇-硅烷修饰活性基团
三维数字孪生引擎与实景互动,案例解析
rem适配
3分钟带你了解微信小程序开发
【C语言万字长文】 宏定义 结构体 共用体 内存对齐知识点总结
@Autowired与@Resource区别
Mysql8.0安装教程
EF Core:基于关系的复杂查询 区分IEnumerable和IQueryable
Day34 LeetCode
Redis安装,基本命令,持久化方式,集群
线性代数学习笔记3-3:逆矩阵的理解
Chapter 10 聚类
什么是轮式里程计
About cross-domain issues
(Reposted) The relationship between hashcode and equals
STL entry basics map and set containers
网站与服务器维护怎么做?
深度自编码网络的集成学习ICPS入侵检测模型
化学试剂磷脂-聚乙二醇-羟基,DSPE-PEG-OH,DSPE-PEG-Hydroxyl,MW:5000