关于spring boot集成jjwt的示例

时间:2025-03-09 07:30:14
  • package ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import .slf4j.Slf4j;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • /**
  • * jjwt相关工具
  • * @author lerry
  • */
  • @Component
  • @Slf4j
  • public class LemtoJwtTokenUtils {
  • private final SecretKey secretKey;
  • private final TemporalAmount expiration;
  • /**
  • *
  • * description: LemtoJwtTokenUtils 构造器
  • * @param secret jwt 密钥
  • * @param minutes 有效期
  • * @author lerry
  • */
  • public LemtoJwtTokenUtils(@Value("${}") String secret,
  • @Value("${}") int minutes) {
  • = (SignatureAlgorithm.HS256);
  • = (minutes);
  • }
  • /**
  • * 加密
  • * description: 使用JWT生成器构造JWT,并使用指定的密钥和算法对其进行签名。
  • * <br>在这里,我们还指定了JWT的发布时间和过期时间。
  • * @param claims jwt的claims
  • * @return
  • * @author lerry
  • */
  • public String generateToken(Map<String, Object> claims) {
  • Instant now = ();
  • return ()
  • .setClaims(claims)
  • .setIssuedAt((now))
  • .setExpiration(((expiration)))
  • .signWith(secretKey,SignatureAlgorithm.HS256)
  • .compact();
  • }
  • /**
  • * 解密
  • * description: 用JWT解析器从JWT中提取声明,并使用指定的密钥验证JWT的签名。
  • * @param token json token
  • * @return
  • * @author lerry
  • */
  • public Claims extractClaims(String token) throws JwtException {
  • return ()
  • .setSigningKey(secretKey)
  • .build()
  • .parseClaimsJws(token)
  • .getBody();
  • }
  • }