JwtUtil.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package com.imed.costaccount.common.token;
  2. import cn.hutool.core.date.DateField;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUtil;
  5. import com.auth0.jwt.JWT;
  6. import com.auth0.jwt.algorithms.Algorithm;
  7. import com.auth0.jwt.exceptions.JWTDecodeException;
  8. import com.auth0.jwt.interfaces.DecodedJWT;
  9. import com.imed.costaccount.common.exception.CostException;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.stereotype.Component;
  12. import java.util.Date;
  13. @Component
  14. public class JwtUtil {
  15. @Value("${cost.jwt.secret}")
  16. private String secret;
  17. @Value("${cost.jwt.expire}")
  18. private Integer expire;
  19. public String createToken(Long userId) {
  20. Date date = DateUtil.offset(new DateTime(), DateField.DAY_OF_YEAR, expire).toJdkDate();
  21. Algorithm algorithm = Algorithm.HMAC256(secret);
  22. String token = JWT.create().withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
  23. return token;
  24. }
  25. public int getUserId(String token) {
  26. try {
  27. DecodedJWT decode = JWT.decode(token);
  28. Integer userId = decode.getClaim("userId").asInt();
  29. return userId;
  30. } catch (JWTDecodeException e) {
  31. throw new CostException(500, "操作非法");
  32. }
  33. }
  34. public void verifierToken(String token) {
  35. Algorithm algorithm = Algorithm.HMAC256(secret);
  36. JWT.require(algorithm).build().verify(token);
  37. }
  38. }