JWTUtil.java 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. package com.ifast.api.util;
  2. import com.auth0.jwt.JWT;
  3. import com.auth0.jwt.JWTVerifier;
  4. import com.auth0.jwt.algorithms.Algorithm;
  5. import com.auth0.jwt.exceptions.InvalidClaimException;
  6. import com.auth0.jwt.exceptions.JWTDecodeException;
  7. import com.auth0.jwt.exceptions.TokenExpiredException;
  8. import com.auth0.jwt.interfaces.Claim;
  9. import com.auth0.jwt.interfaces.DecodedJWT;
  10. import com.ifast.api.config.JWTConfigProperties;
  11. import com.ifast.api.exception.IFastApiException;
  12. import com.ifast.api.pojo.vo.TokenVO;
  13. import com.ifast.api.service.impl.AppUserServiceImpl;
  14. import com.ifast.common.type.EnumErrorCode;
  15. import com.ifast.common.utils.SpringContextHolder;
  16. import com.ifast.sys.domain.UserDO;
  17. import lombok.extern.slf4j.Slf4j;
  18. import org.apache.shiro.authc.AuthenticationException;
  19. import org.apache.shiro.authc.ExpiredCredentialsException;
  20. import org.springframework.stereotype.Component;
  21. import javax.annotation.PostConstruct;
  22. import java.io.UnsupportedEncodingException;
  23. import java.util.Calendar;
  24. import java.util.Date;
  25. /**
  26. * <pre>
  27. * jwt工具类
  28. * </pre>
  29. *
  30. * <small> 2018年4月28日 | Aron</small>
  31. */
  32. @Slf4j
  33. @Component
  34. public class JWTUtil {
  35. private static JWTConfigProperties jwtConfigProperties = null;
  36. @PostConstruct
  37. public void init() {
  38. jwtConfigProperties = SpringContextHolder.getBean(JWTConfigProperties.class);
  39. }
  40. public static String STR_DELIMITER = "\\.";
  41. public static int LEVEL = 3;
  42. public static TokenVO createToken(UserDO user) {
  43. TokenVO vo = new TokenVO();
  44. String token = JWTUtil.sign(user.getId() + "", user.getUsername() + user.getPassword(), AppUserServiceImpl.Holder.jwtConfig.getExpireTime());
  45. String refreshToken = JWTUtil.sign(user.getId() + "", user.getUsername() + user.getPassword(), AppUserServiceImpl.Holder.jwtConfig.getRefreshTokenExpire(), true);
  46. vo.setToken(token);
  47. vo.setRefleshToken(refreshToken);
  48. vo.setTokenExpire(AppUserServiceImpl.Holder.jwtConfig.getExpireTime());
  49. vo.setRefreshTokenExpire(AppUserServiceImpl.Holder.jwtConfig.getRefreshTokenExpire());
  50. return vo;
  51. }
  52. /**
  53. * token是否过期
  54. *
  55. * @return true:过期
  56. */
  57. public static boolean isTokenExpired(String token) {
  58. Date now = Calendar.getInstance().getTime();
  59. DecodedJWT jwt = JWT.decode(token);
  60. return jwt.getExpiresAt().before(now);
  61. }
  62. /**
  63. * <pre>
  64. * </pre>
  65. *
  66. * <small> 2018年4月28日 | Aron</small>
  67. *
  68. * @param token 即jwt
  69. * @param userId 用户id
  70. * @param secret 用户的secret
  71. */
  72. public static void verify(String token, String userId, String secret) {
  73. try {
  74. Algorithm algorithm = Algorithm.HMAC256(secret);
  75. JWTVerifier verifier = JWT.require(algorithm).withClaim(jwtConfigProperties.getUserPrimaryKey(), userId).build();
  76. verifier.verify(token);
  77. } catch (TokenExpiredException exception) {
  78. log.info("token 签名校验失败,过期:{}", token);
  79. throw new ExpiredCredentialsException(EnumErrorCode.apiAuthorizationExpired.getMsg());
  80. } catch (InvalidClaimException exception2) {
  81. log.info("token 签名校验失败,数据异常:{}", token);
  82. throw new AuthenticationException(EnumErrorCode.apiAuthorizationInvalid.getMsg());
  83. } catch (Exception exception3) {
  84. log.info("token 签名校验失败:{}", token);
  85. throw new IFastApiException(EnumErrorCode.apiAuthorizationInvalid.getCodeStr());
  86. }
  87. }
  88. public static void verify(String token, String userId, String secret, boolean isRefreshToken) {
  89. if (isRefreshToken) {
  90. secret += "_REFRESH_TOKEN";
  91. }
  92. verify(token, userId, secret);
  93. }
  94. /**
  95. * <pre>
  96. * 获得token中的信息无需secret解密也能获得
  97. * </pre>
  98. *
  99. * <small> 2018年4月28日 | Aron</small>
  100. *
  101. * @param token token
  102. */
  103. public static String getUserId(String token) {
  104. try {
  105. DecodedJWT jwt = JWT.decode(token);
  106. Claim claim = jwt.getClaim(jwtConfigProperties.getUserPrimaryKey());
  107. return claim.asString();
  108. } catch (JWTDecodeException e) {
  109. log.warn("token解码获取{}失败:{}", jwtConfigProperties.getUserPrimaryKey(), token);
  110. return null;
  111. }
  112. }
  113. /**
  114. * <pre>
  115. * </pre>
  116. *
  117. * <small> 2018年4月28日 | Aron</small>
  118. *
  119. * @param userId 用户标识
  120. * @param secret 加密密钥
  121. * @param expire 有效期,毫秒值
  122. */
  123. public static String sign(String userId, String secret, long expire) {
  124. try {
  125. Date date = new Date(System.currentTimeMillis() + expire);
  126. Algorithm algorithm = Algorithm.HMAC256(secret);
  127. return JWT.create().withClaim(jwtConfigProperties.getUserPrimaryKey(), userId).withExpiresAt(date).sign(algorithm);
  128. } catch (UnsupportedEncodingException e) {
  129. e.printStackTrace();
  130. throw new IFastApiException(EnumErrorCode.apiAuthorizationSignFailed.getCodeStr());
  131. }
  132. }
  133. /**
  134. * <pre>
  135. * </pre>
  136. *
  137. * <small> 2018年4月28日 | Aron</small>
  138. *
  139. * @param userId 用户标识
  140. * @param secret 加密密钥
  141. * @param expire 有效期,毫秒值
  142. */
  143. public static String sign(String userId, String secret, long expire, boolean isRefreshToken) {
  144. if (isRefreshToken) {
  145. secret += "_REFRESH_TOKEN";
  146. }
  147. return sign(userId, secret, expire);
  148. }
  149. }