JWT & JJWT
JWT
本文采用 HS256 编码方式
Tips:你需要知道 JWT 由【标头(Header)、有效载荷(Payload)、签名(Verify Signature)】这三部分组成
- https://github.com/auth0/java-jwt
1. 导包
<!-- jwt 依赖包 -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.18.3</version>
</dependency>
2. 生成一个 key 密钥
Algorithm algorithmHS = Algorithm.HMAC256("my secret");
3. 创建一个 token
try {
Algorithm algorithm = Algorithm.HMAC256("my secret");
String token = JWT.create()
.withIssuer("mlrl")
.sign(algorithm);
log.info((token);
} catch ( exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
输出:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJtbHJsIn0.o4t9ma-6QT6urz63qTlATCQiX8cb3uywO_QPNTxfcwQ
4. 一些token的验证
iss:jwt前发签发者
sub:jwt所面向的用户
aud:接收jwt的乙方
exp:jwt的过期时间,必须要大于签发时间
nbf:定义在什么时间之前,该jwt都是不可用的
iat:jwt的签发时间
jti:jwt的唯一身份表示,主要用来作为一次性token,从而回避重放攻击
- 验证 token 签名是否匹配
try {
Algorithm algorithm = Algorithm.HMAC256("my secret");
String token = JWT.create()
.withIssuer("mlrl")
.sign(algorithm);
// 创建验证 token 的验证工具
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("123")
.build(); //Reusable verifier instance
// 执行验证
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception) {
log.error("验证token 失败" + exception.getMessage());
}
- 验证 token 签名是否匹配
try {
Algorithm algorithm = Algorithm.HMAC256("my secret");
String token = JWT.create()
.withIssuer("mlrl")
.sign(algorithm);
// 输出 token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJtbHJsIn0.Mc7rezSs-Ym-XdFulbqFXqCsis5phSIHbY3VZuCdicQ";
// 创建验证 token 的验证器类
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("123")
.build(); //Reusable verifier instance
// 执行验证
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception) {
log.error("验证token 失败" + exception.getMessage());
}
输出:验证token 失败The Claim 'iss' value doesn't match the required issuer.
原因:创建token的 withIssuer("mlrl") 与 解析的 withIssuer("123") 不一致导致验证失败
- 时间验证(有点迷,博主有点不太明白怎么设置时间)
Time Validation
The JWT token may include DateNumber fields that can be used to validate that:
- The token was issued in a past date “iat” < TODAY
- The token hasn’t expired yet “exp” > TODAY and
- The token can already be used. “nbf” < TODAY
When verifying a token the time validation occurs automatically, resulting in a JWTVerificationException being throw when the values are invalid. If any of the previous fields are missing they won’t be considered in this validation.
To specify a leeway window in which the Token should still be considered valid, use the acceptLeeway() method in the JWTVerifier builder and pass a positive seconds value. This applies to every item listed above.
JWTVerifier verifier = JWT.require(algorithm)
.acceptLeeway(1) // 1 sec for nbf, iat and exp
.build();
You can also specify a custom value for a given Date claim and override the default one for only that claim.
JWTVerifier verifier = JWT.require(algorithm)
.acceptLeeway(1) //1 sec for nbf and iat
.acceptExpiresAt(5)