pow.xml内写入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
main下的test下的软件包内的JwtTest类写
package com.it;
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("it"));//配置秘钥
System.out.println(token);
}
@Test
public void testParse(){
String token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"+
".eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3Mjc2NjQzMzh9" +
".ObH6oogPhZiyJAZCuC0hhUN3HUzTNaxC9weyq9YnGZU";
JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256("it")).build();
DecodedJWT decodedJWT=jwtVerifier.verify(token);
Map<String, Claim> claims=decodedJWT.getClaims();
System.out.println(claims.get("user"));
}
}
测试成功输出:
{"id":1,"username":"张三"}