引入依赖
官网上面链接很多java实现,这里使用java-jwt
1 2 3 4 5
| <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.7.0</version> </dependency>
|
创建util类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class JWTUtils {
private static String secret = "test-jwt";
public static String create(Long uid) { Map<String, Object> header = new HashMap(); header.put("alg", "HS256"); header.put("typ", "JWT");
String token = JWT.create() .withHeader(header) .withExpiresAt(new Date(System.currentTimeMillis() + 30L * 60 * 1000)) .withClaim("uid", uid) .sign(Algorithm.HMAC256(secret)); return token; }
public static DecodedJWT decoded(String token){ JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build(); DecodedJWT decoded = verifier.verify(token); return decoded; } }
|
测试
1 2 3 4 5 6 7 8 9
| public static void main(String[] args) { System.out.println("当前时间:" + new Date()); String token = create(1L); System.out.println("token:" + token);
DecodedJWT decoded = decoded(token); System.out.println("过期时间:" + decoded.getExpiresAt()); System.out.println("uid:" + decoded.getClaim("uid").asLong()); }
|
控制台:
1 2 3 4
| 当前时间:Tue Apr 07 20:48:47 CST 2020 token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjEsImV4cCI6MTU4NjI2NTUyN30.vFel7jyAJpi1YxcFmnohbTDSKXHpC7EH8Kg8aQDmuN8 过期时间:Tue Apr 07 21:18:47 CST 2020 uid:1
|