POM dependencies
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.3</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<!-- Uncomment this next dependency if you are using:
- JDK 10 or earlier, and you want to use RSASSA-PSS (PS256, PS384, PS512) signature algorithms.
- JDK 10 or earlier, and you want to use EdECDH (X25519 or X448) Elliptic Curve Diffie-Hellman encryption.
- JDK 14 or earlier, and you want to use EdDSA (Ed25519 or Ed448) Elliptic Curve signature algorithms.
It is unnecessary for these algorithms on JDK 15 or later.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId> or bcprov-jdk15to18 on JDK 7
<version>1.76</version>
<scope>runtime</scope>
</dependency>
-->
Generate token
PS: Basically the same as java-jwt. It’s just that the latest jjwt has abandoned some APIs and replaced them with new APIs.
① Standard payload:
JwtBuilder provides convenient builder methods for the standard payload defined in the JWT specification.
● issuer: sets the iss(Issuer) Claim jwt issuer
● subject: sets the sub(Subject) Claim jwt is for the user< a i=4> ● audience: sets the aud(Audience) Claim The party that verifies jwt ● expiration: sets the exp(Expiration Time) Claim jwt expiration time ● notBefore: sets the nbf(Not Before) Claim defines that the jwt is not available before a certain time ● issuedAt: sets the iat(Issued At) Claim issuance time ● id: sets the jti(JWT ID) Claim jwt’s unique identity, used as a one-time token to prevent replay attacks. ② Custom payload: ● claime(key, value) ● claime(Map object)
// 创建token密钥的key,并且使用 HMAC-SHA-256 加密算法
private static SecretKey key = Jwts.SIG.HS256.key().build();
/**
* 生成token
* @return
*/
public static String genToken(){
// 2. 构建jwt,将签发人设置为joe,并且使用密钥将签名jwt生成为jws
String jws = Jwts.builder().
subject("Joe"). // setSubject 设置jwt针对的用户
issuer("张三"). // issuer 签发人
claim("name","zhangsan"). // 自定义载荷数据
claim("role","admin"). // 自定义载荷数据
signWith(key). // token加签认证
expiration(new Date(System.currentTimeMillis()+7200*1000)). // 设置token过期时间为2H
compact(); // 生成token字符串
return jws;
}
Two core codes for generating tokens:
SecretKey key = Jwts.SIG.HS256.key().build();
Jwts.builder().setSubject("Joe").signWith(key).compact();
Verify parsing token
/**
* token 校验
* @param key 密钥
* @param token jws
* @return
*/
public static String checkToken(SecretKey key,String token ){
String msg = null;
try {
Jws<Claims> claimsJws = Jwts.parser().
verifyWith(key).
build().
parseSignedClaims(token);
// 获取载荷的一些数据信息
Claims payload = claimsJws.getPayload(); // payload 为一个map对象
String issuer = payload.getIssuer();
Date expiration = payload.getExpiration();
String name = (String)payload.get("name");
String role = (String)payload.get("role");
// 测试就直接打印出去了...
System.out.println("标准载荷:issuer===>"+issuer+"\texpiration=>"+expiration + "自定义载荷数据:"+name+"\t"+role);
return "token正确";
} catch (SignatureException se) {
msg = "密钥错误";
return msg;
}catch (MalformedJwtException me) {
msg = "密钥算法或者密钥转换错误";
return msg;
}catch (MissingClaimException mce) {
msg = "密钥缺少校验数据";
return msg;
}catch (ExpiredJwtException mce) {
msg = "密钥已过期";
return msg;
}catch (JwtException jwte) {
msg = "密钥解析错误";
return msg;
}
}
Complete code
package jwt_test;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;
import javax.crypto.SecretKey;
import java.util.Date;
/**
* jjwt
*/
public class JJwtUtils {
// 创建token密钥的key,并且使用 HMAC-SHA-256 加密算法
private static SecretKey key = Jwts.SIG.HS256.key().build();
/**
* 生成token
* @return
*/
public static String genToken(){
// 2. 构建jwt,将签发人设置为joe,并且使用密钥将签名jwt生成为jws
String jws = Jwts.builder().
subject("Joe"). // setSubject 设置jwt针对的用户
issuer("张三"). // issuer 签发人
claim("name","zhangsan"). // 自定义载荷数据
claim("role","admin"). // 自定义载荷数据
signWith(key). // token加签认证
expiration(new Date(System.currentTimeMillis()+7200*1000)). // 设置token过期时间为2H
compact(); // 生成token字符串
return jws;
}
/**
* token 校验
* @param key 密钥
* @param token jws
* @return
*/
public static String checkToken(SecretKey key,String token ){
String msg = null;
try {
Jws<Claims> claimsJws = Jwts.parser().
verifyWith(key).
build().
parseSignedClaims(token);
// 获取载荷的一些数据信息
Claims payload = claimsJws.getPayload(); // payload 为一个map对象
String issuer = payload.getIssuer();
Date expiration = payload.getExpiration();
String name = (String)payload.get("name");
String role = (String)payload.get("role");
// 测试就直接打印出去了...
System.out.println("标准载荷:issuer===>"+issuer+"\texpiration=>"+expiration + "自定义载荷数据:"+name+"\t"+role);
return "token正确";
} catch (SignatureException se) {
msg = "密钥错误";
return msg;
}catch (MalformedJwtException me) {
msg = "密钥算法或者密钥转换错误";
return msg;
}catch (MissingClaimException mce) {
msg = "密钥缺少校验数据";
return msg;
}catch (ExpiredJwtException mce) {
msg = "密钥已过期";
return msg;
}catch (JwtException jwte) {
msg = "密钥解析错误";
return msg;
}
}
/**
* 测试
*/
public static void main(String[] args) {
String token = genToken();
System.out.println(token);
// 断言测试
// assert Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload().getSubject().equals("Joe");
String res = checkToken(key, token);
System.out.println(res);
}
}