JWTTokenUtil.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package com.njuzr.eaibackend.utils;
  2. import io.jsonwebtoken.*;
  3. import io.jsonwebtoken.security.Keys;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.security.authentication.AuthenticationServiceException;
  7. import org.springframework.security.authentication.CredentialsExpiredException;
  8. import org.springframework.stereotype.Component;
  9. import java.time.Instant;
  10. import java.util.Date;
  11. import java.util.UUID;
  12. @Slf4j
  13. @Component
  14. public class JWTTokenUtil {
  15. @Value("${jwt.secret}")
  16. private String secret; // token生成秘钥
  17. @Value("${jwt.issuer}")
  18. private String issuer; // 发布人
  19. @Value("${jwt.expiration}")
  20. private String expiration; // 过期时间
  21. /**
  22. * 根据用户信息生成token
  23. * @param username
  24. * @return token令牌
  25. */
  26. public String generateToken(String username) {
  27. String uuid = UUID.randomUUID().toString(); // token id
  28. Date exprireDate = Date.from(Instant.now().plusSeconds(Long.parseLong(expiration))); // 过期时间
  29. return Jwts.builder()
  30. // 设置头部信息header
  31. .header()
  32. .add("typ", "JWT")
  33. .add("alg", "HS256")
  34. .and()
  35. // 设置自定义负载信息payload
  36. .claim("username", username)
  37. // 令牌ID
  38. .id(uuid)
  39. // 过期日期
  40. .expiration(exprireDate)
  41. // 签发时间
  42. .issuedAt(new Date())
  43. // 主题
  44. .subject(username)
  45. // 签发者
  46. .issuer(issuer)
  47. // 签名
  48. .signWith(Keys.hmacShaKeyFor(secret.getBytes()), Jwts.SIG.HS256)
  49. .compact();
  50. }
  51. /**
  52. * 解析token
  53. * @param token token
  54. * @return Jws<Claims>
  55. */
  56. public Jws<Claims> parseClaim(String token) {
  57. try {
  58. return Jwts.parser()
  59. .verifyWith(Keys.hmacShaKeyFor(secret.getBytes()))
  60. .build()
  61. .parseSignedClaims(token);
  62. } catch (ExpiredJwtException e) {
  63. // 令牌过期
  64. throw new CredentialsExpiredException("Token has expired", e);
  65. } catch (JwtException e) {
  66. // 其他JWT解析错误
  67. throw new AuthenticationServiceException("Error parsing JWT", e);
  68. }
  69. }
  70. public String parseToken(String token) {
  71. return parseClaim(token).getPayload().getSubject();
  72. }
  73. /**
  74. * 判断token是否未失效
  75. * true表示未失效
  76. */
  77. public boolean isTokenNotExpired(String token) {
  78. Date expiredDate = parseClaim(token).getPayload().getExpiration();
  79. return expiredDate.after(new Date());
  80. }
  81. }