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 }