什么是JWT:
1. JSON Web Token ====》JWT
2. jwt是信息加密的一种方式,一个JWT由三个部分组成:header,payload,signature。分别保存了不同的信息。三个部分在JWT中分别对应英文句号分割出来的三个串
3. payload中通常base64加密,可以被反编译,所以敏感信息尽量不要放到里面
pom.xml导入mvn依赖:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.13.0</version>
</dependency>
applicationTests:
package com.example.smdemo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Calendar;
import java.util.HashMap;
@SpringBootTest
class SmdemoApplicationTests {
@Test
void contextLoads() {
HashMap<String,Object> map = new HashMap<>();
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,600);
String token = JWT.create().
withHeader(map). //header
withClaim("userId",12). //payload
withClaim("userName","张三"). //payload
withExpiresAt(instance.getTime()). //指定令牌过期时间
sign(Algorithm.HMAC256("#AWMAKM4")); //签名
System.out.println(token);
}
@Test
public void test(){
//创建验证对象
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("#AWMAKM4")).build();
DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IuW8oOS4iSIsImV4cCI6MTYxNjQ4MzQyMywidXNlcklkIjoxMn0.vRSbeoupquBUDGeQHhltPUgk5CIQQr7fMAALjmFAIPM");
System.out.println("用户id:"+verify.getClaim("userId").asInt());
System.out.println("用户名:"+verify.getClaim("userName").asString());
System.out.println("过期时间:"+verify.getExpiresAt());
}
}
打印结果:
用户id:12
用户名:张三
过期时间:Tue Mar 23 15:10:23 CST 2021