1、导入jwt依赖
**jwt:json+web+token
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
2、代码示例
请求头+有效载荷+签名**
public class JwtEmp {
public static void main(String[] args) throws InterruptedException {
//签名
Algorithm java2202 = Algorithm.HMAC256("java2202");
long currentTimeMillis = System.currentTimeMillis()+3000;
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("k1","v1");
String token = JWT.create()
//请求头
.withHeader(hashMap)
//有效载荷
.withClaim("name", "admin")
.withClaim("age", 22)
.withClaim("sal", 3000)
//设置过期时间
.withExpiresAt(new Date(currentTimeMillis))
.sign(java2202);
System.out.println("token数据:"+token);
Thread.sleep(4000);
DecodedJWT verify = JWT.require(java2202).build().verify(token);
//验证成功后获取token的数据
String name = verify.getClaim("name").asString();
Integer age = verify.getClaim("age").asInt();
String header = verify.getHeader();
Claim k1 = verify.getHeaderClaim("k1");
System.out.println("值为"+k1.asString());
System.out.println(name);
System.out.println(age);
System.out.println(header);
}
}