JwtUtils.java 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package com.genersoft.iot.vmp.conf.security;
  2. import com.genersoft.iot.vmp.conf.security.dto.JwtUser;
  3. import com.genersoft.iot.vmp.service.IUserApiKeyService;
  4. import com.genersoft.iot.vmp.service.IUserService;
  5. import com.genersoft.iot.vmp.storager.dao.dto.User;
  6. import com.genersoft.iot.vmp.storager.dao.dto.UserApiKey;
  7. import org.jose4j.jwk.JsonWebKey;
  8. import org.jose4j.jwk.JsonWebKeySet;
  9. import org.jose4j.jwk.RsaJsonWebKey;
  10. import org.jose4j.jwk.RsaJwkGenerator;
  11. import org.jose4j.jws.AlgorithmIdentifiers;
  12. import org.jose4j.jws.JsonWebSignature;
  13. import org.jose4j.jwt.JwtClaims;
  14. import org.jose4j.jwt.NumericDate;
  15. import org.jose4j.jwt.consumer.ErrorCodes;
  16. import org.jose4j.jwt.consumer.InvalidJwtException;
  17. import org.jose4j.jwt.consumer.JwtConsumer;
  18. import org.jose4j.jwt.consumer.JwtConsumerBuilder;
  19. import org.jose4j.lang.JoseException;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import org.springframework.beans.factory.InitializingBean;
  23. import org.springframework.stereotype.Component;
  24. import javax.annotation.Resource;
  25. import java.io.BufferedReader;
  26. import java.io.InputStreamReader;
  27. import java.nio.charset.StandardCharsets;
  28. import java.time.LocalDateTime;
  29. import java.time.ZoneOffset;
  30. import java.util.List;
  31. import java.util.Map;
  32. @Component
  33. public class JwtUtils implements InitializingBean {
  34. private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
  35. public static final String HEADER = "access-token";
  36. public static final String API_KEY_HEADER = "api-key";
  37. private static final String AUDIENCE = "Audience";
  38. private static final String keyId = "3e79646c4dbc408383a9eed09f2b85ae";
  39. /**
  40. * token过期时间(分钟)
  41. */
  42. public static final long EXPIRATION_TIME = 30 * 24 * 60;
  43. private static RsaJsonWebKey rsaJsonWebKey;
  44. private static IUserService userService;
  45. private static IUserApiKeyService userApiKeyService;
  46. public static String getApiKeyHeader() {
  47. return API_KEY_HEADER;
  48. }
  49. @Resource
  50. public void setUserService(IUserService userService) {
  51. JwtUtils.userService = userService;
  52. }
  53. @Resource
  54. public void setUserApiKeyService(IUserApiKeyService userApiKeyService) {
  55. JwtUtils.userApiKeyService = userApiKeyService;
  56. }
  57. @Override
  58. public void afterPropertiesSet() {
  59. try {
  60. rsaJsonWebKey = generateRsaJsonWebKey();
  61. } catch (JoseException e) {
  62. logger.error("生成RsaJsonWebKey报错。", e);
  63. }
  64. }
  65. /**
  66. * 创建密钥对
  67. *
  68. * @throws JoseException JoseException
  69. */
  70. private RsaJsonWebKey generateRsaJsonWebKey() throws JoseException {
  71. RsaJsonWebKey rsaJsonWebKey = null;
  72. try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/jwk.json"), StandardCharsets.UTF_8))) {
  73. String jwkJson = reader.readLine();
  74. JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jwkJson);
  75. List<JsonWebKey> jsonWebKeys = jsonWebKeySet.getJsonWebKeys();
  76. if (!jsonWebKeys.isEmpty()) {
  77. JsonWebKey jsonWebKey = jsonWebKeys.get(0);
  78. if (jsonWebKey instanceof RsaJsonWebKey) {
  79. rsaJsonWebKey = (RsaJsonWebKey) jsonWebKey;
  80. }
  81. }
  82. } catch (Exception e) {
  83. // ignored
  84. }
  85. if (rsaJsonWebKey == null) {
  86. // 生成一个RSA密钥对,该密钥对将用于JWT的签名和验证,包装在JWK中
  87. rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
  88. // 给JWK一个密钥ID
  89. rsaJsonWebKey.setKeyId(keyId);
  90. }
  91. return rsaJsonWebKey;
  92. }
  93. public static String createToken(String username, Long expirationTime, Map<String, Object> extra) {
  94. try {
  95. /*
  96. * “iss” (issuer) 发行人
  97. * “sub” (subject) 主题
  98. * “aud” (audience) 接收方 用户
  99. * “exp” (expiration time) 到期时间
  100. * “nbf” (not before) 在此之前不可用
  101. * “iat” (issued at) jwt的签发时间
  102. */
  103. JwtClaims claims = new JwtClaims();
  104. claims.setGeneratedJwtId();
  105. claims.setIssuedAtToNow();
  106. // 令牌将过期的时间 分钟
  107. if (expirationTime != null) {
  108. claims.setExpirationTimeMinutesInTheFuture(expirationTime);
  109. }
  110. claims.setNotBeforeMinutesInThePast(0);
  111. claims.setSubject("login");
  112. claims.setAudience(AUDIENCE);
  113. //添加自定义参数,必须是字符串类型
  114. claims.setClaim("userName", username);
  115. if (extra != null) {
  116. extra.forEach(claims::setClaim);
  117. }
  118. //jws
  119. JsonWebSignature jws = new JsonWebSignature();
  120. //签名算法RS256
  121. jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
  122. jws.setKeyIdHeaderValue(keyId);
  123. jws.setPayload(claims.toJson());
  124. jws.setKey(rsaJsonWebKey.getPrivateKey());
  125. //get token
  126. return jws.getCompactSerialization();
  127. } catch (JoseException e) {
  128. logger.error("[Token生成失败]: {}", e.getMessage());
  129. }
  130. return null;
  131. }
  132. public static String createToken(String username, Long expirationTime) {
  133. return createToken(username, expirationTime, null);
  134. }
  135. public static String createToken(String username) {
  136. return createToken(username, EXPIRATION_TIME);
  137. }
  138. public static String getHeader() {
  139. return HEADER;
  140. }
  141. public static JwtUser verifyToken(String token) {
  142. JwtUser jwtUser = new JwtUser();
  143. try {
  144. JwtConsumer consumer = new JwtConsumerBuilder()
  145. //.setRequireExpirationTime()
  146. //.setMaxFutureValidityInMinutes(5256000)
  147. .setAllowedClockSkewInSeconds(30)
  148. .setRequireSubject()
  149. //.setExpectedIssuer("")
  150. .setExpectedAudience(AUDIENCE)
  151. .setVerificationKey(rsaJsonWebKey.getPublicKey())
  152. .build();
  153. JwtClaims claims = consumer.processToClaims(token);
  154. NumericDate expirationTime = claims.getExpirationTime();
  155. if (expirationTime != null) {
  156. // 判断是否即将过期, 默认剩余时间小于5分钟未即将过期
  157. // 剩余时间 (秒)
  158. long timeRemaining = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)) - expirationTime.getValue();
  159. if (timeRemaining < 5 * 60) {
  160. jwtUser.setStatus(JwtUser.TokenStatus.EXPIRING_SOON);
  161. } else {
  162. jwtUser.setStatus(JwtUser.TokenStatus.NORMAL);
  163. }
  164. } else {
  165. jwtUser.setStatus(JwtUser.TokenStatus.NORMAL);
  166. }
  167. Long apiKeyId = claims.getClaimValue("apiKeyId", Long.class);
  168. if (apiKeyId != null) {
  169. UserApiKey userApiKey = userApiKeyService.getUserApiKeyById(apiKeyId.intValue());
  170. if (userApiKey == null || !userApiKey.isEnable()) {
  171. jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
  172. }
  173. }
  174. String username = (String) claims.getClaimValue("userName");
  175. User user = userService.getUserByUsername(username);
  176. jwtUser.setUserName(username);
  177. jwtUser.setPassword(user.getPassword());
  178. jwtUser.setRoleId(user.getRole().getId());
  179. jwtUser.setUserId(user.getId());
  180. return jwtUser;
  181. } catch (InvalidJwtException e) {
  182. if (e.hasErrorCode(ErrorCodes.EXPIRED)) {
  183. jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
  184. } else {
  185. jwtUser.setStatus(JwtUser.TokenStatus.EXCEPTION);
  186. }
  187. return jwtUser;
  188. } catch (Exception e) {
  189. logger.error("[Token解析失败]: {}", e.getMessage());
  190. jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
  191. return jwtUser;
  192. }
  193. }
  194. }