欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jwt 的一个例子

程序员文章站 2022-04-08 14:00:10
...
解析和 生成 token
[quote]
https://blog.csdn.net/qq_40081976/article/details/79046825
[/quote]


package com.zyd.jwt;

import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtHelper {

private final static String base64Secret = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";
private final static int expiresSecond = 172800000;

public static Claims parseJWT(String jsonWebToken) {
try {
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret))
.parseClaimsJws(jsonWebToken).getBody();
return claims;
} catch (Exception ex) {
return null;
}
}

public static String createJWT(String username, String roles, String privileges) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);

//生成签名**
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

//添加构成JWT的参数
JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
.claim("user_name", username)
.claim("user_role", roles)
.claim("user_privilege", privileges)
.signWith(signatureAlgorithm, signingKey);
//添加Token过期时间
if (expiresSecond >= 0) {
long expMillis = nowMillis + expiresSecond;
Date exp = new Date(expMillis);
builder.setExpiration(exp).setNotBefore(now);
}

//生成JWT
return builder.compact();
}
}

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>