java · 2024-07-31 0

JWT 使用

1.pom 依赖

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.14.0</version>
</dependency>

2.java

// 秘钥,你可以随便取,可以取的难一点
public static final String SECRET = "123456";

// HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload),secret)
@Test
public void testJWT() {
    Map<String, Object> headers = new HashMap<>();
    // 过期时间,60s
    Calendar expires = Calendar.getInstance();
    expires.add(Calendar.SECOND, 5);

    // 创建 jwt
    String jwtToken = JWT.create()
            // 第一部分Header
            .withHeader(headers)
            // 第二部分Payload
            .withClaim("userId", 20)
            .withClaim("userName", "zhangsan")
            .withExpiresAt(expires.getTime())
            // 第三部分Signature
            .sign(Algorithm.HMAC256(SECRET));
    System.out.println(jwtToken);

    // 创建一个验证的对象
    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
    DecodedJWT verify = jwtVerifier.verify(jwtToken);
    System.out.println(verify.getClaim("userId").asInt());
    System.out.println(verify.getClaim("userName").asString());
    System.out.println("过期时间:" + verify.getExpiresAt());
}