JwtUtil.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package cn.seecoder.seecoderbokserver.util;
  2. import cn.seecoder.seecoderbokserver.exception.MyServiceException;
  3. import com.auth0.jwt.JWT;
  4. import com.auth0.jwt.JWTVerifier;
  5. import com.auth0.jwt.algorithms.Algorithm;
  6. import com.auth0.jwt.exceptions.JWTVerificationException;
  7. import com.auth0.jwt.exceptions.TokenExpiredException;
  8. import com.auth0.jwt.interfaces.Claim;
  9. import com.auth0.jwt.interfaces.DecodedJWT;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.stereotype.Component;
  12. /**
  13. * @author mars
  14. */
  15. @Component
  16. public class JwtUtil {
  17. private static String jwtSecret;
  18. @Value("${jwt.secret}")
  19. public void setJwtSecret(String jwtSecret) { //通过set让static方法读取配置文件中的值
  20. JwtUtil.jwtSecret = jwtSecret;
  21. }
  22. public static String getJwtSecret() {
  23. return JwtUtil.jwtSecret;
  24. }
  25. public static Claim parseJwt(String token) {
  26. // jwtSecret
  27. JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build();
  28. DecodedJWT decodedjwt;
  29. try {
  30. decodedjwt = jwtVerifier.verify(token);
  31. } catch (TokenExpiredException e) {
  32. throw new MyServiceException("A0230", "用户登陆已过期");
  33. } catch (JWTVerificationException | IllegalArgumentException e) { //解析错误 或者 token写错
  34. e.printStackTrace();
  35. throw new MyServiceException("A0200", "登陆失败");
  36. }
  37. // if (decodedjwt.getClaim("exp").asDate().before(new Date())) {
  38. // throw new MyServiceException("A0230", "用户登陆已过期");
  39. // }
  40. return decodedjwt.getClaim("user_info");
  41. }
  42. }