当前位置:网站首页>JWT-JSON WEB TOKEN
JWT-JSON WEB TOKEN
2022-07-06 06:08:00 【雪峰.贵】
一、JWT是什么?

二、JWT的组成
- Header: 记录令牌的类型,签名的算法名。{“alg”:“HS256”,“type”:“JWT”}
- Payload:记录用户信息。{“username”:“GXF”,“id”:“1”}
- Signature:防止Token被篡改,提高安全性。根据Header和Payload计算出来的一个字符串。
三、Token组成
token=BASE64(Header).BASE64(Payload).BASE64(Signature)
四、Signature的组成
Signature是由Header里的alg指定的算法计算出来。
Signature=指定的算法(BASE64(Header).BASE64(Payload),密钥)
五、使用
- 加依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
- 加配置
jwt:
secret: 123456 #密钥
# 有效期,单位秒,默认2周
expire-time-in-second: 1209600
- 加工具类
import com.google.common.collect.Maps;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequiredArgsConstructor
@SuppressWarnings("WeakerAccess")
@Component
public class JwtOperator {
/** * 秘钥 * - 默认aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt */
@Value("${secret:aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt}")
private String secret;
/** * 有效期,单位秒 * - 默认2周 */
@Value("${expire-time-in-second:1209600}")
private Long expirationTimeInSecond;
/** * 从token中获取claim * * @param token token * @return claim */
public Claims getClaimsFromToken(String token) {
try {
return Jwts.parser()
.setSigningKey(this.secret.getBytes())
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
log.error("token解析错误", e);
throw new IllegalArgumentException("Token invalided.");
}
}
/** * 获取token的过期时间 * * @param token token * @return 过期时间 */
public Date getExpirationDateFromToken(String token) {
return getClaimsFromToken(token)
.getExpiration();
}
/** * 判断token是否过期 * * @param token token * @return 已过期返回true,未过期返回false */
private Boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
/** * 计算token的过期时间 * * @return 过期时间 */
public Date getExpirationTime() {
return new Date(System.currentTimeMillis() + this.expirationTimeInSecond * 1000);
}
/** * 为指定用户生成token * * @param claims 用户信息 * @return token */
public String generateToken(Map<String, Object> claims) {
Date createdTime = new Date();
Date expirationTime = this.getExpirationTime();
byte[] keyBytes = secret.getBytes();
SecretKey key = Keys.hmacShaKeyFor(keyBytes);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(createdTime)
.setExpiration(expirationTime)
// 你也可以改用你喜欢的算法
// 支持的算法详见:https://github.com/jwtk/jjwt#features
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
/** * 判断token是否非法 * * @param token token * @return 未过期返回true,否则返回false */
public Boolean validateToken(String token) {
return !isTokenExpired(token);
}
// public static void main(String[] args) {
// // 1. 初始化
// JwtOperator jwtOperator = new JwtOperator();
// jwtOperator.expirationTimeInSecond = 1209600L;
// jwtOperator.secret = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt";
//
// // 2.设置用户信息
// HashMap<String, Object> objectObjectHashMap = Maps.newHashMap();
// objectObjectHashMap.put("id", "1");
//
// // 测试1: 生成token
// String token = jwtOperator.generateToken(objectObjectHashMap);
// // 会生成类似该字符串的内容: eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk4MTcsImV4cCI6MTU2Njc5OTQxN30.27_QgdtTg4SUgxidW6ALHFsZPgMtjCQ4ZYTRmZroKCQ
// System.out.println(token);
//
// // 将我改成上面生成的token!!!
// String someToken = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1OTQ1NjIsImV4cCI6MTU2NjgwNDE2Mn0.PAvWPcQAZnSlYKNbZr4O1l9aA4LPphuq0OG2QIs7O5E\n";
// // 测试2: 如果能token合法且未过期,返回true
// Boolean validateToken = jwtOperator.validateToken(someToken);
// System.out.println(validateToken);
//
// // 测试3: 获取用户信息
// Claims claims = jwtOperator.getClaimsFromToken(someToken);
// System.out.println(claims);
//
// // 将我改成你生成的token的第一段(以.为边界)
// String encodedHeader = "eyJhbGciOiJIUzI1NiJ9";
// // 测试4: 解密Header
// byte[] header = Base64.decodeBase64(encodedHeader.getBytes());
// System.out.println(new String(header));
//
// // 将我改成你生成的token的第二段(以.为边界)
// String encodedPayload = "eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk1NDEsImV4cCI6MTU2Njc5OTE0MX0";
// // 测试5: 解密Payload
// byte[] payload = Base64.decodeBase64(encodedPayload.getBytes());
// System.out.println(new String(payload));
//
// // 测试6: 这是一个被篡改的token,因此会报异常,说明JWT是安全的
// jwtOperator.validateToken("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpYXQiOjE1NjU1ODk3MzIsImV4cCI6MTU2Njc5OTMzMn0.nDv25ex7XuTlmXgNzGX46LqMZItVFyNHQpmL9UQf-aUxxx");
// }
}
边栏推荐
- Significance of unit testing
- Commodity price visualization
- Application of Lie group in gtsam
- 對數據安全的思考(轉載)
- 曼哈顿距离和-打印菱形
- 全链路压测:构建三大模型
- Raised a kitten
- [Baiwen smart home] first day of the course_ Learn Embedded and understand the development mode of bare metal and RTOS
- JMeter做接口测试,如何提取登录Cookie
- [C language syntax] the difference between typedef struct and struct
猜你喜欢

10m25dcf484c8g (FPGA) amy-6m-0002 BGA GPS module

MySQL之数据类型

曼哈顿距离与曼哈顿矩形-打印回字型矩阵

How to use the container reflection method encapsulated by thinkphp5.1 in business code

VINS-Mono: A Robust and Versatile Monocular Visual-Inertial State Estimator

JMeter做接口测试,如何提取登录Cookie

Overview of three core areas of Mathematics: algebra

SQLMAP使用教程(三)实战技巧二

(中)苹果有开源,但又怎样呢?

The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
随机推荐
10M25DCF484C8G(FPGA) AMY-6M-0002 BGA GPS模块
误差的基本知识
【Tera Term】黑猫带你学TTL脚本——嵌入式开发中串口自动化神技能
LeetCode 1200. 最小绝对差
Postman核心功能解析-参数化和测试报告
Embedded point test of app
leaflet 地图
Request forwarding and redirection
The latest 2022 review of "graph classification research"
nodejs实现微博第三方登录
单元测试的意义
[postman] collections - run the imported data file of the configuration
Title 1093: character reverse order
Leaflet map
异常检测方法总结
【C语言】qsort函数
[leetcode] day96 - the first unique character & ransom letter & letter ectopic word
properties文件
C language bubble sort
IPv6 comprehensive experiment