JWT
"的生成与解析;<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
【说明01】
JWT
";【代码01】
@Test
public void testGenerateJwt() {
// 准备`claims`
Map<String, Object> claims = new HashMap<>();
claims.put("id", 1);
claims.put("name", "SUNxRUN");
// 准备`过期时间(设置:10年)`
Date expirationDate = new Date(System.currentTimeMillis() + 525600 * 10 * 60 * 1000);
// 准备`密钥`
String secretKey = "1234567890";
// JWT的组成部分:Header(头)、Payload(载荷)、Signature(签名)
String jwt = Jwts.builder()
// Header:用于配置算法与此结果数据的类型
// 通常配置两个属性:tye(类型)、alg(算法)
.setHeaderParam("typ", "jwt")
.setHeaderParam("alg", "HS256")
// Payload:用于配置需要封装到JWT中的数据
.setClaims(claims)
.setExpiration(expirationDate)
// Signature:用于指定算法与密钥(盐)
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
System.out.println(jwt);
}
【结果01】
eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiU1VOeFJVTiIsImlkIjoxLCJleHAiOjE3MDc0NzcyNDR9.stHmCODCatUhNQ6M9_tYQfR4ay0rRd0wQIMZgYXKyhY
【说明01】
JWT
";【代码01】
@Test
public void testParseJwt() {
// `密钥`
String secretKey = "1234567890";
// `JWT`
String jwt = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiU1VOeFJVTiIsImlkIjoxLCJleHAiOjE3MDc0NzcyNDR9.stHmCODCatUhNQ6M9_tYQfR4ay0rRd0wQIMZgYXKyhY";
Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
Object id = claims.get("id");
System.out.println("id=" + id);
Object name = claims.get("name");
System.out.println("name=" + name);
}
【结果01】
id=1
name=SUNxRUN