Commit e8b2ca46862565b7b6d2f05c3f45f7873afe044e
1 parent
dc37f667
将生成jwt令牌和验证jwt令牌时使用的公钥私钥由固定值修改为每次启动服务时动态生产;剔除jwt token中包含的password和roleId,防止密码泄露。
Showing
2 changed files
with
54 additions
and
33 deletions
src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java
| 1 | package com.genersoft.iot.vmp.conf.security; | 1 | package com.genersoft.iot.vmp.conf.security; |
| 2 | 2 | ||
| 3 | import com.genersoft.iot.vmp.conf.security.dto.JwtUser; | 3 | import com.genersoft.iot.vmp.conf.security.dto.JwtUser; |
| 4 | -import org.jose4j.json.JsonUtil; | 4 | +import com.genersoft.iot.vmp.service.IUserService; |
| 5 | +import com.genersoft.iot.vmp.storager.dao.dto.User; | ||
| 5 | import org.jose4j.jwk.RsaJsonWebKey; | 6 | import org.jose4j.jwk.RsaJsonWebKey; |
| 7 | +import org.jose4j.jwk.RsaJwkGenerator; | ||
| 6 | import org.jose4j.jws.AlgorithmIdentifiers; | 8 | import org.jose4j.jws.AlgorithmIdentifiers; |
| 7 | import org.jose4j.jws.JsonWebSignature; | 9 | import org.jose4j.jws.JsonWebSignature; |
| 8 | import org.jose4j.jwt.JwtClaims; | 10 | import org.jose4j.jwt.JwtClaims; |
| @@ -14,45 +16,69 @@ import org.jose4j.jwt.consumer.JwtConsumerBuilder; | @@ -14,45 +16,69 @@ import org.jose4j.jwt.consumer.JwtConsumerBuilder; | ||
| 14 | import org.jose4j.lang.JoseException; | 16 | import org.jose4j.lang.JoseException; |
| 15 | import org.slf4j.Logger; | 17 | import org.slf4j.Logger; |
| 16 | import org.slf4j.LoggerFactory; | 18 | import org.slf4j.LoggerFactory; |
| 19 | +import org.springframework.beans.factory.InitializingBean; | ||
| 20 | +import org.springframework.stereotype.Component; | ||
| 17 | 21 | ||
| 18 | -import java.security.PrivateKey; | 22 | +import javax.annotation.Resource; |
| 19 | import java.time.LocalDateTime; | 23 | import java.time.LocalDateTime; |
| 20 | import java.time.ZoneOffset; | 24 | import java.time.ZoneOffset; |
| 21 | 25 | ||
| 22 | -public class JwtUtils { | 26 | +@Component |
| 27 | +public class JwtUtils implements InitializingBean { | ||
| 23 | 28 | ||
| 24 | private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); | 29 | private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); |
| 25 | 30 | ||
| 26 | private static final String HEADER = "access-token"; | 31 | private static final String HEADER = "access-token"; |
| 27 | - private static final String AUDIENCE = "Audience"; | ||
| 28 | 32 | ||
| 29 | - private static final long EXPIRED_THRESHOLD = 10 * 60; | 33 | + private static final String AUDIENCE = "Audience"; |
| 30 | 34 | ||
| 31 | private static final String keyId = "3e79646c4dbc408383a9eed09f2b85ae"; | 35 | private static final String keyId = "3e79646c4dbc408383a9eed09f2b85ae"; |
| 32 | - private static final String privateKeyStr = "{\"kty\":\"RSA\",\"kid\":\"3e79646c4dbc408383a9eed09f2b85ae\",\"alg\":\"RS256\",\"n\":\"gndmVdiOTSJ5et2HIeTM5f1m61x5ojLUi5HDfvr-jRrESQ5kbKuySGHVwR4QhwinpY1wQqBnwc80tx7cb_6SSqsTOoGln6T_l3k2Pb54ClVnGWiW_u1kmX78V2TZOsVmZmwtdZCMi-2zWIyAdIEXE-gncIehoAgEoq2VAhaCURbJWro_EwzzQwNmCTkDodLAx4npXRd_qSu0Ayp0txym9OFovBXBULRvk4DPiy3i_bPUmCDxzC46pTtFOe9p82uybTehZfULZtXXqRm85FL9n5zkrsTllPNAyEGhgb0RK9sE5nK1m_wNNysDyfLC4EFf1VXTrKm14XNVjc2vqLb7Mw\",\"e\":\"AQAB\",\"d\":\"ed7U_k3rJ4yTk70JtRSIfjKGiEb67BO1TabcymnljKO7RU8nage84zZYuSu_XpQsHk6P1f0Gzxkicghm_Er-FrfVn2pp70Xu52z3yRd6BJUgWLDFk97ngScIyw5OiULKU9SrZk2frDpftNCSUcIgb50F8m0QAnBa_CdPsQKbuuhLv8V8tBAV7F_lAwvSBgu56wRo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 | - private static final String publicKeyStr = "{\"kty\":\"RSA\",\"kid\":\"3e79646c4dbc408383a9eed09f2b85ae\",\"alg\":\"RS256\",\"n\":\"gndmVdiOTSJ5et2HIeTM5f1m61x5ojLUi5HDfvr-jRrESQ5kbKuySGHVwR4QhwinpY1wQqBnwc80tx7cb_6SSqsTOoGln6T_l3k2Pb54ClVnGWiW_u1kmX78V2TZOsVmZmwtdZCMi-2zWIyAdIEXE-gncIehoAgEoq2VAhaCURbJWro_EwzzQwNmCTkDodLAx4npXRd_qSu0Ayp0txym9OFovBXBULRvk4DPiy3i_bPUmCDxzC46pTtFOe9p82uybTehZfULZtXXqRm85FL9n5zkrsTllPNAyEGhgb0RK9sE5nK1m_wNNysDyfLC4EFf1VXTrKm14XNVjc2vqLb7Mw\",\"e\":\"AQAB\"}"; | ||
| 34 | 36 | ||
| 35 | /** | 37 | /** |
| 36 | * token过期时间(分钟) | 38 | * token过期时间(分钟) |
| 37 | */ | 39 | */ |
| 38 | public static final long expirationTime = 30 * 24 * 60; | 40 | public static final long expirationTime = 30 * 24 * 60; |
| 39 | 41 | ||
| 40 | - public static String createToken(String username, String password, Integer roleId) { | 42 | + private static RsaJsonWebKey rsaJsonWebKey; |
| 43 | + | ||
| 44 | + private static IUserService userService; | ||
| 45 | + | ||
| 46 | + @Resource | ||
| 47 | + public void setUserService(IUserService userService) { | ||
| 48 | + JwtUtils.userService = userService; | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + @Override | ||
| 52 | + public void afterPropertiesSet() { | ||
| 41 | try { | 53 | try { |
| 42 | - /** | 54 | + rsaJsonWebKey = generateRsaJsonWebKey(); |
| 55 | + } catch (JoseException e) { | ||
| 56 | + logger.error("生成RsaJsonWebKey报错。", e); | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + /** | ||
| 61 | + * 创建密钥对 | ||
| 62 | + * @throws JoseException JoseException | ||
| 63 | + */ | ||
| 64 | + private RsaJsonWebKey generateRsaJsonWebKey() throws JoseException { | ||
| 65 | + // 生成一个RSA密钥对,该密钥对将用于JWT的签名和验证,包装在JWK中 | ||
| 66 | + RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048); | ||
| 67 | + // 给JWK一个密钥ID | ||
| 68 | + rsaJsonWebKey.setKeyId(keyId); | ||
| 69 | + return rsaJsonWebKey; | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + public static String createToken(String username) { | ||
| 73 | + try { | ||
| 74 | + /* | ||
| 43 | * “iss” (issuer) 发行人 | 75 | * “iss” (issuer) 发行人 |
| 44 | - * | ||
| 45 | * “sub” (subject) 主题 | 76 | * “sub” (subject) 主题 |
| 46 | - * | ||
| 47 | * “aud” (audience) 接收方 用户 | 77 | * “aud” (audience) 接收方 用户 |
| 48 | - * | ||
| 49 | * “exp” (expiration time) 到期时间 | 78 | * “exp” (expiration time) 到期时间 |
| 50 | - * | ||
| 51 | * “nbf” (not before) 在此之前不可用 | 79 | * “nbf” (not before) 在此之前不可用 |
| 52 | - * | ||
| 53 | * “iat” (issued at) jwt的签发时间 | 80 | * “iat” (issued at) jwt的签发时间 |
| 54 | */ | 81 | */ |
| 55 | - //Payload | ||
| 56 | JwtClaims claims = new JwtClaims(); | 82 | JwtClaims claims = new JwtClaims(); |
| 57 | claims.setGeneratedJwtId(); | 83 | claims.setGeneratedJwtId(); |
| 58 | claims.setIssuedAtToNow(); | 84 | claims.setIssuedAtToNow(); |
| @@ -62,9 +88,7 @@ public class JwtUtils { | @@ -62,9 +88,7 @@ public class JwtUtils { | ||
| 62 | claims.setSubject("login"); | 88 | claims.setSubject("login"); |
| 63 | claims.setAudience(AUDIENCE); | 89 | claims.setAudience(AUDIENCE); |
| 64 | //添加自定义参数,必须是字符串类型 | 90 | //添加自定义参数,必须是字符串类型 |
| 65 | - claims.setClaim("username", username); | ||
| 66 | - claims.setClaim("password", password); | ||
| 67 | - claims.setClaim("roleId", roleId); | 91 | + claims.setClaim("userName", username); |
| 68 | 92 | ||
| 69 | //jws | 93 | //jws |
| 70 | JsonWebSignature jws = new JsonWebSignature(); | 94 | JsonWebSignature jws = new JsonWebSignature(); |
| @@ -73,12 +97,10 @@ public class JwtUtils { | @@ -73,12 +97,10 @@ public class JwtUtils { | ||
| 73 | jws.setKeyIdHeaderValue(keyId); | 97 | jws.setKeyIdHeaderValue(keyId); |
| 74 | jws.setPayload(claims.toJson()); | 98 | jws.setPayload(claims.toJson()); |
| 75 | 99 | ||
| 76 | - PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyStr)).getPrivateKey(); | ||
| 77 | - jws.setKey(privateKey); | 100 | + jws.setKey(rsaJsonWebKey.getPrivateKey()); |
| 78 | 101 | ||
| 79 | //get token | 102 | //get token |
| 80 | - String idToken = jws.getCompactSerialization(); | ||
| 81 | - return idToken; | 103 | + return jws.getCompactSerialization(); |
| 82 | } catch (JoseException e) { | 104 | } catch (JoseException e) { |
| 83 | logger.error("[Token生成失败]: {}", e.getMessage()); | 105 | logger.error("[Token生成失败]: {}", e.getMessage()); |
| 84 | } | 106 | } |
| @@ -90,7 +112,6 @@ public class JwtUtils { | @@ -90,7 +112,6 @@ public class JwtUtils { | ||
| 90 | return HEADER; | 112 | return HEADER; |
| 91 | } | 113 | } |
| 92 | 114 | ||
| 93 | - | ||
| 94 | public static JwtUser verifyToken(String token) { | 115 | public static JwtUser verifyToken(String token) { |
| 95 | 116 | ||
| 96 | JwtUser jwtUser = new JwtUser(); | 117 | JwtUser jwtUser = new JwtUser(); |
| @@ -103,7 +124,7 @@ public class JwtUtils { | @@ -103,7 +124,7 @@ public class JwtUtils { | ||
| 103 | .setRequireSubject() | 124 | .setRequireSubject() |
| 104 | //.setExpectedIssuer("") | 125 | //.setExpectedIssuer("") |
| 105 | .setExpectedAudience(AUDIENCE) | 126 | .setExpectedAudience(AUDIENCE) |
| 106 | - .setVerificationKey(new RsaJsonWebKey(JsonUtil.parseJson(publicKeyStr)).getPublicKey()) | 127 | + .setVerificationKey(rsaJsonWebKey.getPublicKey()) |
| 107 | .build(); | 128 | .build(); |
| 108 | 129 | ||
| 109 | JwtClaims claims = consumer.processToClaims(token); | 130 | JwtClaims claims = consumer.processToClaims(token); |
| @@ -113,26 +134,26 @@ public class JwtUtils { | @@ -113,26 +134,26 @@ public class JwtUtils { | ||
| 113 | long timeRemaining = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)) - expirationTime.getValue(); | 134 | long timeRemaining = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)) - expirationTime.getValue(); |
| 114 | if (timeRemaining < 5 * 60) { | 135 | if (timeRemaining < 5 * 60) { |
| 115 | jwtUser.setStatus(JwtUser.TokenStatus.EXPIRING_SOON); | 136 | jwtUser.setStatus(JwtUser.TokenStatus.EXPIRING_SOON); |
| 116 | - }else { | 137 | + } else { |
| 117 | jwtUser.setStatus(JwtUser.TokenStatus.NORMAL); | 138 | jwtUser.setStatus(JwtUser.TokenStatus.NORMAL); |
| 118 | } | 139 | } |
| 119 | 140 | ||
| 120 | - String username = (String) claims.getClaimValue("username"); | ||
| 121 | - String password = (String) claims.getClaimValue("password"); | ||
| 122 | - Long roleId = (Long) claims.getClaimValue("roleId"); | 141 | + String username = (String) claims.getClaimValue("userName"); |
| 142 | + User user = userService.getUserByUsername(username); | ||
| 143 | + | ||
| 123 | jwtUser.setUserName(username); | 144 | jwtUser.setUserName(username); |
| 124 | - jwtUser.setPassword(password); | ||
| 125 | - jwtUser.setRoleId(roleId.intValue()); | 145 | + jwtUser.setPassword(user.getPassword()); |
| 146 | + jwtUser.setRoleId(user.getRole().getId()); | ||
| 126 | 147 | ||
| 127 | return jwtUser; | 148 | return jwtUser; |
| 128 | } catch (InvalidJwtException e) { | 149 | } catch (InvalidJwtException e) { |
| 129 | if (e.hasErrorCode(ErrorCodes.EXPIRED)) { | 150 | if (e.hasErrorCode(ErrorCodes.EXPIRED)) { |
| 130 | jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); | 151 | jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); |
| 131 | - }else { | 152 | + } else { |
| 132 | jwtUser.setStatus(JwtUser.TokenStatus.EXCEPTION); | 153 | jwtUser.setStatus(JwtUser.TokenStatus.EXCEPTION); |
| 133 | } | 154 | } |
| 134 | return jwtUser; | 155 | return jwtUser; |
| 135 | - }catch (Exception e) { | 156 | + } catch (Exception e) { |
| 136 | logger.error("[Token解析失败]: {}", e.getMessage()); | 157 | logger.error("[Token解析失败]: {}", e.getMessage()); |
| 137 | jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); | 158 | jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); |
| 138 | return jwtUser; | 159 | return jwtUser; |
src/main/java/com/genersoft/iot/vmp/vmanager/user/UserController.java
| @@ -57,7 +57,7 @@ public class UserController { | @@ -57,7 +57,7 @@ public class UserController { | ||
| 57 | if (user == null) { | 57 | if (user == null) { |
| 58 | throw new ControllerException(ErrorCode.ERROR100.getCode(), "用户名或密码错误"); | 58 | throw new ControllerException(ErrorCode.ERROR100.getCode(), "用户名或密码错误"); |
| 59 | }else { | 59 | }else { |
| 60 | - String jwt = JwtUtils.createToken(username, password, user.getRole().getId()); | 60 | + String jwt = JwtUtils.createToken(username); |
| 61 | response.setHeader(JwtUtils.getHeader(), jwt); | 61 | response.setHeader(JwtUtils.getHeader(), jwt); |
| 62 | user.setAccessToken(jwt); | 62 | user.setAccessToken(jwt); |
| 63 | } | 63 | } |