1. 引入jar包
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.0</version> </dependency>
2. 實現
1 public class JWTUtil { 2 //過期時間15分鍾 3 private static final long EXPIRE_TIME = 15*60*1000; 4 //token秘鑰,設置的復雜點這里用一串uuid,並用HMAC256加密的 5 private static final String TOKEN_SECRET = "JFKDJFKGFGFGIFG8R9589589"; 6 7 //生成token 8 public static String generatorToken(String userName,Stringn userId) { 9 //過期時間 10 Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME ); 11 //秘鑰及加密算法 12 Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); 13 //設置頭部信息 14 Map<String,Object> header = new HashMap<String,Object>(2); 15 header.put("type","JWT"); 16 header.put("alg","HS256"); 17 //附帶用戶信息,生成token 18 return JWT.create() 19 .withHeader(header) 20 .withClaim("userName",userName) 21 .withClaim("userId",userId) 22 .withExpiresAt(date) 23 .sign(algorithm); 24 } 25 }