jjwt官網鏈接:https://github.com/jwtk/jjwt
POM 依賴
<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>
-->
生成token
PS: 基本和java-jwt使用一致。只是最新的jjwt舍棄了一些api,換了新的api
① 標準載荷:
JwtBuilder為JWT規范中定義的標準載荷提供了方便的構建器方法。
● issuer: sets the iss(Issuer) Claim jwt簽發者
● subject: sets the sub(Subject) Claim jwt針對的用戶
● audience: sets the aud(Audience) Claim 校驗jwt的一方
● expiration: sets the exp(Expiration Time) Claim jwt過期時間
● notBefore: sets the nbf(Not Before) Claim 定義在某個時間前該jwt是不可用的
● issuedAt: sets the iat(Issued At) Claim 簽發時間
● id: sets the jti(JWT ID) Claim jwt的唯一身份標識,作一次性token,防重放攻擊。
② 自定義載荷:
● claime(key,value)
● claime(Map對象)
// 創建token密鑰的key,并且使用 HMAC-SHA-256 加密算法
private static SecretKey key = Jwts.SIG.HS256.key().build();/*** 生成token* @return*/
public static String genToken(){// 2. 構建jwt,將簽發人設置為joe,并且使用密鑰將簽名jwt生成為jwsString 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過期時間為2Hcompact(); // 生成token字符串return jws;
}
生成token的兩句核心代碼:
SecretKey key = Jwts.SIG.HS256.key().build();
Jwts.builder().setSubject("Joe").signWith(key).compact();
驗證解析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;}
}
完整代碼
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生成為jwsString 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過期時間為2Hcompact(); // 生成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);}}