直接上源代码
@Test
public void testJwetsRead() {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("sdalfkjleiwfjioerjglni*^#&8dsfasdfrghtgru39847j*(&&^#*yr894yr8934thfklKNDhfiuerhfgoie8gorggkhsdlrghdsioghviosrhgvosrihtgor45ut9034759384509347328o5rh");
SecretKey signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
String jwsString = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNzE0ZDcwYi1lNjJhLTQ2ZWYtYWE0ZS0wYTNmNDA5ZGJhMjMiLCJpYXQiOjE3NDczMTA1MDUsInN1YiI6IkhhcHB5IEJpcnRoZGF5IiwiaXNzIjoiQmFpamluZyIsImV4cCI6MTc0NzM5NjkwNX0.n0R0BLwknSCb19q-Tn9g6L9MoUGK6t-CxeNmHvCUQ40";
Jws<Claims> claimsJws = Jwts.parser()
.verifyWith(signingKey)
.build()
.parseSignedClaims(jwsString);
System.out.println(claimsJws.getBody());
}
getBody() 也可以放到 Jwts 的链式编程结构中。
直接输出一个 JSON String 。
结果
{
jti=1714d70b-e62a-46ef-aa4e-0a3f409dba23,
iat=1747310505,
sub=Happy Birthday, i
ss=Baijing,
exp=1747396905
}
见 生成 jwt 串的方法, Spring and Java-CSDN博客
的源代码了解前情。
@Test
public void testJJwt() {
String id = UUID.randomUUID().toString();
String issuer = "Baijing";
String subject = "Happy Birthday";
Long ttlMillis = (long) (1000 * 60 * 60 * 24);
//The JWT signature algorithm we will be using to sign the token
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//We will sign our JWT with our ApiKey secret
// byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("sdalfkjleiwfjioerjglni*^#&8dsfasdfrghtgru39847j*(&&^#*yr894yr8934thfklKNDhfiuerhfgoie8gorggkhsdlrghdsioghviosrhgvosrihtgor45ut9034759384509347328o5rh");
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
//Let's set the JWT Claims
JwtBuilder builder = Jwts.builder().setId(id)
.issuedAt(now)
.subject(subject)
.issuer(issuer)
.signWith(signatureAlgorithm, signingKey);
//if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
System.out.println(builder.compact());
//Builds the JWT and serializes it to a compact, URL-safe string
// return builder.compact();
}
生成 Jwt String 的代码。