JJWT 是 開源的、用於 java 創建和驗證JSON Web令牌的庫。
網址:https://github.com/jwtk/jjwt
簡單示例:
生成JSON Web令牌
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import java.security.Key; import javax.crypto.SecretKey; public class JwsTest { public static void main(String[] args){ try { //生成令牌首生需要祕鑰,一般從配置文件讀取 Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); //以下注釋代碼把 Key 轉爲16進制字符串 byte[] keybyte=key.getEncoded(); String keystr=ByteHexUtil.byteArr2HexStr(keybyte);//字符串祕鑰 System.out.println(keystr); SecretKey secretKey=Keys.hmacShaKeyFor(keybyte); String jws = Jwts.builder() .setSubject("Joe")//set 用戶標識,和基他需要屬性 .signWith(secretKey)//祕鑰 .compact(); System.out.println(jws);//生成令牌 }catch(Exception e) { e.printStackTrace(); } } }
效驗令牌
import javax.crypto.SecretKey; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; public class JwsTest1 { public static void main(String[] args) { try{ //上個類的祕鑰 byte[] keybyte=ByteHexUtil.hexStr2ByteArr("8cd037fce22e5dd292abf02a3ff02539e0c9512ef86fdafa2fc6fce26ae17c6f"); SecretKey secretKey=Keys.hmacShaKeyFor(keybyte); //上個類的令牌 String jws="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJKb2UifQ.dTJloyna-gkfz89nBS07iUOy3jD_aDv8VwBLnFkBijo"; String body=Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jws).getBody().getSubject(); System.out.println(body); }catch(Exception e){ e.printStackTrace(); } } }