优化JWT自动识别header中的算法,并可自定义header中key的顺序

This commit is contained in:
Looly 2022-09-13 19:17:57 +08:00
parent d14483a698
commit 65c91c5aef
4 changed files with 55 additions and 6 deletions

View File

@ -7,6 +7,7 @@
### 🐣新特性
* 【core 】 BooleanUtil的andOfWrap和orOfWrap()忽略nullissue#2599@Github
* 【jwt 】 优化JWT自动识别header中的算法并可自定义header中key的顺序issue#I5QRUO@Gitee
### 🐞Bug修复
-------------------------------------------------------------------------------------------------------------

View File

@ -112,12 +112,17 @@ public class JWT implements RegisteredPayload<JWT> {
}
/**
* 设置密钥默认算法是HS256(HmacSHA256)
* 设置密钥如果头部指定了算法直接使用否则默认算法是HS256(HmacSHA256)
*
* @param key 密钥
* @return this
*/
public JWT setKey(byte[] key) {
// 检查头信息中是否有算法信息
final String claim = (String) this.header.getClaim(JWTHeader.ALGORITHM);
if (StrUtil.isNotBlank(claim)) {
return setSigner(JWTSignerUtil.createSigner(claim, key));
}
return setSigner(JWTSignerUtil.hs256(key));
}
@ -309,9 +314,15 @@ public class JWT implements RegisteredPayload<JWT> {
public String sign(JWTSigner signer) {
Assert.notNull(signer, () -> new JWTException("No Signer provided!"));
// 检查tye信息
final String type = (String) this.header.getClaim(JWTHeader.TYPE);
if (StrUtil.isBlank(type)) {
this.header.setClaim(JWTHeader.TYPE, "JWT");
}
// 检查头信息中是否有算法信息
final String claim = (String) this.header.getClaim(JWTHeader.ALGORITHM);
if (StrUtil.isBlank(claim)) {
final String algorithm = (String) this.header.getClaim(JWTHeader.ALGORITHM);
if (StrUtil.isBlank(algorithm)) {
this.header.setClaim(JWTHeader.ALGORITHM,
AlgorithmUtil.getId(signer.getAlgorithm()));
}

View File

@ -32,9 +32,7 @@ public class JWTHeader extends Claims {
/**
* 构造初始化默认(typ=JWT)
*/
public JWTHeader() {
setClaim(TYPE, "JWT");
}
public JWTHeader() {}
/**
* 增加kid头信息

View File

@ -0,0 +1,39 @@
package cn.hutool.jwt;
import org.junit.Assert;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
public class IssueI5QRUOTest {
@Test
public void createTokenTest(){
// https://jwt.io/
// 自定义header顺序
final Map<String, Object> header = new LinkedHashMap<String, Object>(){
{
put(JWTHeader.ALGORITHM, "HS384");
put(JWTHeader.TYPE, "JWT");
}
};
final Map<String, Object> payload = new LinkedHashMap<String, Object>(){
{
put("sub", "1234567890");
put("name", "John Doe");
put("iat", 1516239022);
}
};
final String token = JWTUtil.createToken(header, payload, "123456".getBytes());
Assert.assertEquals("eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9." +
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ." +
"3Ywq9NlR3cBST4nfcdbR-fcZ8374RHzU50X6flKvG-tnWFMalMaHRm3cMpXs1NrZ", token);
final boolean verify = JWT.of(token).setKey("123456".getBytes()).verify();
Assert.assertTrue(verify);
}
}