Springboot 整合 JWT
jwt依赖
<!-- JWT-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- 坑!! 不引入下面依赖JWT报错-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
JwtUtil
public class JwtUtil {
String signature = "密钥";
public void jwt() {
JwtBuilder jwtBuilder = Jwts.builder();
String jwtToken = jwtBuilder
// header
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg", "HS256")
// payload 存信息
.claim("userName", "william")
.claim("role", "admin")
.setSubject("jwt-test")
// 24H过期
.setExpiration(DateUtil.tomorrow())
.setId(UUID.randomUUID().toString())
// signature
.signWith(SignatureAlgorithm.HS256, signature)
.compact();
System.out.println(jwtToken);
}
public void parse() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IndpbGxpYW0iLCJyb2xlIjoiYWRtaW4iLCJzdWIiOiJqd3QtdGVzdCIsImV4cCI6MTYyNzAxOTI0MCwianRpIjoiOWU3NDBkNjEtN2ZhMi00NWQxLWFkZmEtYmM0MzRhNzYwNDdkIn0.0tes-dlR3pE4FkOix8olBW0t7z-VsxN7WkK5uWDtB68";
JwtParser parser = Jwts.parser();
Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
Claims jwsBody = claimsJws.getBody();
System.out.println(jwsBody);
System.out.println(jwsBody.getExpiration());
}
}