引入maven依赖坐标
<!--java-jwt坐标-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.13.0</version>
</dependency>
<!--单元测试坐标-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>3.1.2</version>
</dependency>
JwtTest
package com.lin.springboot01;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtTest {
@Test
public void testGen(){
Map<String,Object> claims = new HashMap<>();
claims.put("id",1);
claims.put("username","张三");
//生成jwt的代码
String token = JWT.create()
.withClaim("user",claims)//添加载荷
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60/60*12))//添加过期时间
.sign(Algorithm.HMAC256("lin2332"));//指定算法配置密钥
System.out.println(token);
}
}
密钥生成成功
校验密钥
package com.lin.springboot01;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtTest {
@Test
public void testGen(){
Map<String,Object> claims = new HashMap<>();
claims.put("id",1);
claims.put("username","张三");
//生成jwt的代码
String token = JWT.create()
.withClaim("user",claims)//添加载荷
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))//添加过期时间
.sign(Algorithm.HMAC256("lin2332"));//指定算法配置密钥
System.out.println(token);
}
@Test
public void testParse(){
//定义字符串,模拟用户传递过来的token
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
".eyJleHAiOjE2OTk3MTA5NDcsInVzZXIiOnsiaWQiOjEsInVzZXJuYW1lIjoi5byg5LiJIn19" +
".3CZM1OXRzVzRLCwfe5GrWIFcrJhy49XSjbQeIib-0SI";
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("lin2332")).build();
DecodedJWT decodedJWT = jwtVerifier.verify(token);
Map<String,Claim> claims = decodedJWT.getClaims();
System.out.println(claims.get("user"));
}
}
jwt解析结果: