Springboot 整合 JWT

jwt依赖

  1. <!-- JWT-->
  2. <dependency>
  3. <groupId>io.jsonwebtoken</groupId>
  4. <artifactId>jjwt</artifactId>
  5. <version>0.9.1</version>
  6. </dependency>
  7. <!-- 坑!! 不引入下面依赖JWT报错-->
  8. <dependency>
  9. <groupId>javax.xml.bind</groupId>
  10. <artifactId>jaxb-api</artifactId>
  11. <version>2.3.0</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>com.sun.xml.bind</groupId>
  15. <artifactId>jaxb-impl</artifactId>
  16. <version>2.3.0</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>com.sun.xml.bind</groupId>
  20. <artifactId>jaxb-core</artifactId>
  21. <version>2.3.0</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>javax.activation</groupId>
  25. <artifactId>activation</artifactId>
  26. <version>1.1.1</version>
  27. </dependency>

JwtUtil

  1. public class JwtUtil {
  2. String signature = "密钥";
  3. public void jwt() {
  4. JwtBuilder jwtBuilder = Jwts.builder();
  5. String jwtToken = jwtBuilder
  6. // header
  7. .setHeaderParam("typ", "JWT")
  8. .setHeaderParam("alg", "HS256")
  9. // payload 存信息
  10. .claim("userName", "william")
  11. .claim("role", "admin")
  12. .setSubject("jwt-test")
  13. // 24H过期
  14. .setExpiration(DateUtil.tomorrow())
  15. .setId(UUID.randomUUID().toString())
  16. // signature
  17. .signWith(SignatureAlgorithm.HS256, signature)
  18. .compact();
  19. System.out.println(jwtToken);
  20. }
  21. public void parse() {
  22. String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IndpbGxpYW0iLCJyb2xlIjoiYWRtaW4iLCJzdWIiOiJqd3QtdGVzdCIsImV4cCI6MTYyNzAxOTI0MCwianRpIjoiOWU3NDBkNjEtN2ZhMi00NWQxLWFkZmEtYmM0MzRhNzYwNDdkIn0.0tes-dlR3pE4FkOix8olBW0t7z-VsxN7WkK5uWDtB68";
  23. JwtParser parser = Jwts.parser();
  24. Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
  25. Claims jwsBody = claimsJws.getBody();
  26. System.out.println(jwsBody);
  27. System.out.println(jwsBody.getExpiration());
  28. }
  29. }