后续读取的文章 read jwt 的源代码,Spring Java-CSDN博客
能看到 jwt 的解析
后续将自己生成的 jwt 拷贝到这里;就能看到 jwt 的解析结果。是否和自己定义的相同。
先见代码,为敬:
public void testJWT() {
Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
Date notBefore = new Date(System.currentTimeMillis());
String jws = Jwts.builder()
.issuer("Baijing")
.subject("Happy Birthday")
.audience().add("wucaimu").and()
.expiration(expiration) //a java.util.Date
.notBefore(notBefore) //a java.util.Date
.issuedAt(new Date()) // for example, now
.id(UUID.randomUUID().toString()) //just an example id
.compact();
System.out.println(jws);
}
这里的解释,见官方文档 GitHub - jwtk/jjwt: Java JWT: JSON Web Token for Java and Android
极简的方式生成 jwt 字串
@Test
public void testJWT() {
SecretKey key = Jwts.SIG.HS256.key().build();
String jws = Jwts.builder().subject("BaiJing").signWith(key).compact();
System.out.println(jws);
}
代码均已完成测试;有效。
完备的代码
@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("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(); // 去掉打印语句,能返回值
}
代码 来源: https://web.archive.org/web/20230426235608/https://stormpath.com/blog/jwt-java-create-verify
How to Create and verify JWTs in Java
为何选择 JJwt 见 JSON Web Tokens - jwt.io 的 library ; 支持的比较健全。
解析令牌
import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
.parseClaimsJws(jwt).getBody();
System.out.println("ID: " + claims.getId());
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issuer: " + claims.getIssuer());
System.out.println("Expiration: " + claims.getExpiration());
}