引入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.2.1</version>
</dependency>
生成和解析token
@SpringBootTest
class DemoApplicationTests {
@Test
//生成jwt令牌
void genToken() {
JWTCreator.Builder builder = JWT.create();
Map<String, Object> headers=new HashMap<>();
headers.put("typ","jwt");
headers.put("alg","hs256");
Map<String, Object> claims=new HashMap<>();
claims.put("id",1);
claims.put("username","张三");
String token=builder.withHeader(headers)
.withClaim("user",claims)
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))//设置失效日期,12小时后过期
.sign(Algorithm.HMAC256("mykey"));//加密时所用的密钥
System.out.println(token);
}
//解析并验证jwt令牌,验证不通过则抛出异常
@Test
void parseToken(){
//将genToken打印的字符串复制到这里
String token="*****.*****.******";
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("mykey"))//算法HMAC256要与上面的相同,mykey也要一样
.build();
DecodedJWT decodedJWT = verifier.verify(token);//验证token
Map<String, Object> user = decodedJWT.getClaim("user").asMap();//将放入token的键为user的数据取出来
System.out.println(user.get("username"));
}
}