From 07a8ef9e256c70a3a5b15782add81dcad1e2ffc2 Mon Sep 17 00:00:00 2001 From: panlinlin <648540858@qq.com> Date: 星期五, 14 六月 2024 00:03:57 +0800 Subject: [PATCH] SIP只有一个监听时,直接返回 --- src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java | 169 ++++++++++++++++++++++++++++++++++++++++++------------- 1 files changed, 128 insertions(+), 41 deletions(-) diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java b/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java index 57911b0..eacff18 100644 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java +++ b/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java @@ -1,8 +1,14 @@ package com.genersoft.iot.vmp.conf.security; import com.genersoft.iot.vmp.conf.security.dto.JwtUser; -import org.jose4j.json.JsonUtil; +import com.genersoft.iot.vmp.service.IUserApiKeyService; +import com.genersoft.iot.vmp.service.IUserService; +import com.genersoft.iot.vmp.storager.dao.dto.User; +import com.genersoft.iot.vmp.storager.dao.dto.UserApiKey; +import org.jose4j.jwk.JsonWebKey; +import org.jose4j.jwk.JsonWebKeySet; import org.jose4j.jwk.RsaJsonWebKey; +import org.jose4j.jwk.RsaJwkGenerator; import org.jose4j.jws.AlgorithmIdentifiers; import org.jose4j.jws.JsonWebSignature; import org.jose4j.jwt.JwtClaims; @@ -14,57 +20,119 @@ import org.jose4j.lang.JoseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.stereotype.Component; -import java.security.PrivateKey; +import javax.annotation.Resource; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; -public class JwtUtils { +@Component +public class JwtUtils implements InitializingBean { private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); - private static final String HEADER = "access-token"; + public static final String HEADER = "access-token"; + + public static final String API_KEY_HEADER = "api-key"; + private static final String AUDIENCE = "Audience"; - private static final long EXPIRED_THRESHOLD = 10 * 60; - private static final String keyId = "3e79646c4dbc408383a9eed09f2b85ae"; - 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_lAwvSBgu56wRo3hPz5dWH8YeXM7XBfQ9viFMNEKd21sP_j5C7ueUnXT66nBxe3ZJEU3iuMYM6D6dB_KW2GfZC6WmTgvGhhxJD0h7aYmfjkD99MDleB7SkpbvoODOqiQ5Epb7Nyh6kv5u4KUv2CJYtATLZkUeMkQ\",\"p\":\"uBUjWPWtlGksmOqsqCNWksfqJvMcnP_8TDYN7e4-WnHL4N-9HjRuPDnp6kHvCIEi9SEfxm7gNxlRcWegvNQr3IZCz7TnCTexXc5NOklB9OavWFla6u-s3Thn6Tz45-EUjpJr0VJMxhO-KxGmuTwUXBBp4vN6K2qV6rQNFmgkWzk\",\"q\":\"tW_i7cCec56bHkhITL_79dXHz_PLC_f7xlynmlZJGU_d6mqOKmLBNBbTMLnYW8uAFiFzWxDeDHh1o5uF0mSQR-Z1Fg35OftnpbWpy0Cbc2la5WgXQjOwtG1eLYIY2BD3-wQ1VYDBCvowr4FDi-sngxwLqvwmrJ0xjhi99O-Gzcs\",\"dp\":\"q1d5jE85Hz_6M-eTh_lEluEf0NtPEc-vvhw-QO4V-cecNpbrCBdTWBmr4dE3NdpFeJc5ZVFEv-SACyei1MBEh0ItI_pFZi4BmMfy2ELh8ptaMMkTOESYyVy8U7veDq9RnBcr5i1Nqr0rsBkA77-9T6gzdvycBZdzLYAkAmwzEvk\",\"dq\":\"q29A2K08Crs-jmp2Bi8Q_8QzvIX6wSBbwZ4ir24AO-5_HNP56IrPS0yV2GCB0pqCOGb6_Hz_koDvhtuYoqdqvMVAtMoXR3YJBUaVXPt65p4RyNmFwIPe31zHs_BNUTsXVRMw4c16mci03-Af1sEm4HdLfxAp6sfM3xr5wcnhcek\",\"qi\":\"rHPgVTyHUHuYzcxfouyBfb1XAY8nshwn0ddo81o1BccD4Z7zo5It6SefDHjxCAbcmbiCcXBSooLcY-NF5FMv3fg19UE21VyLQltHcVjRRp2tRs4OHcM8yaXIU2x6N6Z6BP2tOksHb9MOBY1wAQzFOAKg_G4Sxev6-_6ud6RISuc\"}"; - 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\"}"; /** * token杩囨湡鏃堕棿(鍒嗛挓) */ - public static final long expirationTime = 30; + public static final long EXPIRATION_TIME = 30 * 24 * 60; - public static String createToken(String username, String password) { + private static RsaJsonWebKey rsaJsonWebKey; + + private static IUserService userService; + + private static IUserApiKeyService userApiKeyService; + + public static String getApiKeyHeader() { + return API_KEY_HEADER; + } + + @Resource + public void setUserService(IUserService userService) { + JwtUtils.userService = userService; + } + + @Resource + public void setUserApiKeyService(IUserApiKeyService userApiKeyService) { + JwtUtils.userApiKeyService = userApiKeyService; + } + + @Override + public void afterPropertiesSet() { try { - /** + rsaJsonWebKey = generateRsaJsonWebKey(); + } catch (JoseException e) { + logger.error("鐢熸垚RsaJsonWebKey鎶ラ敊銆�", e); + } + } + + /** + * 鍒涘缓瀵嗛挜瀵� + * + * @throws JoseException JoseException + */ + private RsaJsonWebKey generateRsaJsonWebKey() throws JoseException { + RsaJsonWebKey rsaJsonWebKey = null; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/jwk.json"), StandardCharsets.UTF_8))) { + String jwkJson = reader.readLine(); + JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jwkJson); + List<JsonWebKey> jsonWebKeys = jsonWebKeySet.getJsonWebKeys(); + if (!jsonWebKeys.isEmpty()) { + JsonWebKey jsonWebKey = jsonWebKeys.get(0); + if (jsonWebKey instanceof RsaJsonWebKey) { + rsaJsonWebKey = (RsaJsonWebKey) jsonWebKey; + } + } + } catch (Exception e) { + // ignored + } + if (rsaJsonWebKey == null) { + // 鐢熸垚涓�涓猂SA瀵嗛挜瀵癸紝璇ュ瘑閽ュ灏嗙敤浜嶫WT鐨勭鍚嶅拰楠岃瘉锛屽寘瑁呭湪JWK涓� + rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048); + // 缁橨WK涓�涓瘑閽D + rsaJsonWebKey.setKeyId(keyId); + } + return rsaJsonWebKey; + } + + public static String createToken(String username, Long expirationTime, Map<String, Object> extra) { + try { + /* * 鈥渋ss鈥� (issuer) 鍙戣浜� - * * 鈥渟ub鈥� (subject) 涓婚 - * * 鈥渁ud鈥� (audience) 鎺ユ敹鏂� 鐢ㄦ埛 - * * 鈥渆xp鈥� (expiration time) 鍒版湡鏃堕棿 - * * 鈥渘bf鈥� (not before) 鍦ㄦ涔嬪墠涓嶅彲鐢� - * * 鈥渋at鈥� (issued at) jwt鐨勭鍙戞椂闂� */ - //Payload JwtClaims claims = new JwtClaims(); claims.setGeneratedJwtId(); claims.setIssuedAtToNow(); // 浠ょ墝灏嗚繃鏈熺殑鏃堕棿 鍒嗛挓 - claims.setExpirationTimeMinutesInTheFuture(expirationTime); + if (expirationTime != null) { + claims.setExpirationTimeMinutesInTheFuture(expirationTime); + } claims.setNotBeforeMinutesInThePast(0); claims.setSubject("login"); claims.setAudience(AUDIENCE); //娣诲姞鑷畾涔夊弬鏁�,蹇呴』鏄瓧绗︿覆绫诲瀷 - claims.setClaim("username", username); - claims.setClaim("password", password); - + claims.setClaim("userName", username); + if (extra != null) { + extra.forEach(claims::setClaim); + } //jws JsonWebSignature jws = new JsonWebSignature(); //绛惧悕绠楁硶RS256 @@ -72,23 +140,27 @@ jws.setKeyIdHeaderValue(keyId); jws.setPayload(claims.toJson()); - PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyStr)).getPrivateKey(); - jws.setKey(privateKey); + jws.setKey(rsaJsonWebKey.getPrivateKey()); //get token - String idToken = jws.getCompactSerialization(); - return idToken; + return jws.getCompactSerialization(); } catch (JoseException e) { logger.error("[Token鐢熸垚澶辫触]锛� {}", e.getMessage()); } - return null; + } + + public static String createToken(String username, Long expirationTime) { + return createToken(username, expirationTime, null); + } + + public static String createToken(String username) { + return createToken(username, EXPIRATION_TIME); } public static String getHeader() { return HEADER; } - public static JwtUser verifyToken(String token) { @@ -96,40 +168,55 @@ try { JwtConsumer consumer = new JwtConsumerBuilder() - .setRequireExpirationTime() - .setMaxFutureValidityInMinutes(5256000) + //.setRequireExpirationTime() + //.setMaxFutureValidityInMinutes(5256000) .setAllowedClockSkewInSeconds(30) .setRequireSubject() //.setExpectedIssuer("") .setExpectedAudience(AUDIENCE) - .setVerificationKey(new RsaJsonWebKey(JsonUtil.parseJson(publicKeyStr)).getPublicKey()) + .setVerificationKey(rsaJsonWebKey.getPublicKey()) .build(); JwtClaims claims = consumer.processToClaims(token); NumericDate expirationTime = claims.getExpirationTime(); - // 鍒ゆ柇鏄惁鍗冲皢杩囨湡, 榛樿鍓╀綑鏃堕棿灏忎簬5鍒嗛挓鏈嵆灏嗚繃鏈� - // 鍓╀綑鏃堕棿 锛堢锛� - long timeRemaining = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)) - expirationTime.getValue(); - if (timeRemaining < 5 * 60) { - jwtUser.setStatus(JwtUser.TokenStatus.EXPIRING_SOON); - }else { + if (expirationTime != null) { + // 鍒ゆ柇鏄惁鍗冲皢杩囨湡, 榛樿鍓╀綑鏃堕棿灏忎簬5鍒嗛挓鏈嵆灏嗚繃鏈� + // 鍓╀綑鏃堕棿 锛堢锛� + long timeRemaining = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)) - expirationTime.getValue(); + if (timeRemaining < 5 * 60) { + jwtUser.setStatus(JwtUser.TokenStatus.EXPIRING_SOON); + } else { + jwtUser.setStatus(JwtUser.TokenStatus.NORMAL); + } + } else { jwtUser.setStatus(JwtUser.TokenStatus.NORMAL); } - String username = (String) claims.getClaimValue("username"); - String password = (String) claims.getClaimValue("password"); + Long apiKeyId = claims.getClaimValue("apiKeyId", Long.class); + if (apiKeyId != null) { + UserApiKey userApiKey = userApiKeyService.getUserApiKeyById(apiKeyId.intValue()); + if (userApiKey == null || !userApiKey.isEnable()) { + jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); + } + } + + String username = (String) claims.getClaimValue("userName"); + User user = userService.getUserByUsername(username); + jwtUser.setUserName(username); - jwtUser.setPassword(password); + jwtUser.setPassword(user.getPassword()); + jwtUser.setRoleId(user.getRole().getId()); + jwtUser.setUserId(user.getId()); return jwtUser; } catch (InvalidJwtException e) { if (e.hasErrorCode(ErrorCodes.EXPIRED)) { jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); - }else { + } else { jwtUser.setStatus(JwtUser.TokenStatus.EXCEPTION); } return jwtUser; - }catch (Exception e) { + } catch (Exception e) { logger.error("[Token瑙f瀽澶辫触]锛� {}", e.getMessage()); jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED); return jwtUser; -- Gitblit v1.8.0