浏览代码

修改token为公钥私钥验证

15810770710@163.com 3 年之前
父节点
当前提交
77993403ff

+ 5 - 0
pom.xml

@@ -56,6 +56,11 @@
             <artifactId>libCSCipher</artifactId>
             <version>2.2.18</version>
         </dependency>
+        <dependency>
+            <groupId>org.bitbucket.b_c</groupId>
+            <artifactId>jose4j</artifactId>
+            <version>0.7.4</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 20 - 0
src/main/java/com/jkcredit/query/record/constant/CommonConstant.java

@@ -36,4 +36,24 @@ public class CommonConstant {
     public static final String PARAM_ERROR_CODE = "604";
 
     public static final String PARAM_ERROR = "参数错误";
+
+    public static final String TOKEN_PRIVATE_KEY = "{\n" +
+            "    \"p\": \"7pgQYHumeUJqZzoM_v_UG2yT_QsqCR7gqV_gbiNspQhFL_FgnXU8wXxT71oCz3r2ONRV_n54Fc9YVH5bahDLn9mhrICNp1bigxbDKbSWUSLT4s3opf1FeMa5cPkpNKKsPf3OeiB19QESW2dmtr0G2hk2nZo5WteNPBGZQSL4WA0\",\n" +
+            "    \"kty\": \"RSA\",\n" +
+            "    \"q\": \"oZaOnB4fhhPuimY0yI3tWg6o7HFAKqx8GXCvrsZ1HEMZxWdsCbNJ3daol4ZnRMCvS6i9VonNSNTd-k599BzjJ3YaUWl5a5GzaLgNfvAMFBVic1thzee0MaR90bFfUF2qjpuB7sKtVhDVztoJX7Kd1JaZyTUn5toT8aNNgI3a9Wc\",\n" +
+            "    \"d\": \"Z82t7Bx3plb8fu2D51u8Kjr1SYq6ghfSjfNqjfBhumUY1BRQ5nI2gnsDTnhJ7G8MK2dtRoABK6NgR7sibO-x66bHjr-aFFLA9UY67SDrWepewjuNX8Fsa3-cc-jWj22ry300npDx1deT_WFDPkyTBzI4o_nmXGbTzJ2VSLOIIt9__4fHvln-muKeGwvWShx5Lv4kw--K62_2CVCSYpnyg95ogu5P-LG19Ufd-RNX4WGokyZ2Zgf_j0xdzgi3l-pBy96BY_uPrIwvxdjIB2wCdvM1Edzm61VZF6_79UAdR9ZFQp_0V5P2UZyxX98zkCeVngq4oPX-jirRxlDUTwIaoQ\",\n" +
+            "    \"e\": \"AQAB\",\n" +
+            "    \"kid\": \"jiaokexinyong\",\n" +
+            "    \"qi\": \"QVtlKH-bFaGQSvuiHoyvoNBTLwm4UXzUtgbxZ-0fKs1mzcrZ4769aT1f0Q0_6pOFPfPvSL9GTCZOYlSRtrSTmgCfvAO0bdcX8ZH4TYWJvDc6haqsq2jOopQiuGITF91w9iWaLTMmFQaecknBzRpN-VI54x_RumjqsmR8oc1uC64\",\n" +
+            "    \"dp\": \"t8UsKARVTuSW6_dMd0Q47P6OZcKpl-jOheaxCGQElIBwOeMi1WStbSIDzEF6FLDS4Sa7LY_fknznvfytEF7rV63a1vEVKiTDxtBLdd4AQXIf3XtXjDItxj7aKmffEwmQvRa2aF6EPDedGgXkmS-zDV2KMY3OS2fnArNTZVY4Dik\",\n" +
+            "    \"dq\": \"lq7JSfglOWi410K8EhGXtpVZHTP2vFSgXTDiAz950eMY0ybAbsNMLJySFsr03f44-XrfJSXX0wT-Av7TIaMWiKPvot-SpKb4AL0xiJ_dA5V1e1FKATMCrBBSbArVcSIHfHizT60m6s1ENGLKvvzXhXjy69iv3uyaEIlSKoEeIB0\",\n" +
+            "    \"n\": \"lpn0UCAe2Hr45I8xYLnnr_lJinBqWDH9FfRleUXLsiX3TUMbA6rWnEnAiROcX83ntnuBCtfOYC_xvHdLyFZRFT6nArFdwhiOxNoqrpKI2HmlK0m9X0VG9XtXXP7EZ6qOdT_QR9i9XoPDGBTb4s0pQZDJECHKOD-QlEMzj-Jak3FQhba3imQeVKd5fX5tKUHlnxipwLfQbkcHpQ2soTrZpq_ApjUDr-oElJnBErOTuiAICnS_zkCM2__6CDXpXn_XSEz3d7a169lit8ORF1ynYlz8t0E1TpGMwEaVJIPdNK3U1TCICBzSGEs-wGMSjlrWTG98BsCTnsbgaX8m4kHeOw\"\n" +
+            "}";
+    public static final String TOKEN_PUBLIC_KEY = "{\n" +
+            "    \"kty\": \"RSA\",\n" +
+            "    \"e\": \"AQAB\",\n" +
+            "    \"kid\": \"jiaokexinyong\",\n" +
+            "    \"n\": \"lpn0UCAe2Hr45I8xYLnnr_lJinBqWDH9FfRleUXLsiX3TUMbA6rWnEnAiROcX83ntnuBCtfOYC_xvHdLyFZRFT6nArFdwhiOxNoqrpKI2HmlK0m9X0VG9XtXXP7EZ6qOdT_QR9i9XoPDGBTb4s0pQZDJECHKOD-QlEMzj-Jak3FQhba3imQeVKd5fX5tKUHlnxipwLfQbkcHpQ2soTrZpq_ApjUDr-oElJnBErOTuiAICnS_zkCM2__6CDXpXn_XSEz3d7a169lit8ORF1ynYlz8t0E1TpGMwEaVJIPdNK3U1TCICBzSGEs-wGMSjlrWTG98BsCTnsbgaX8m4kHeOw\"\n" +
+            "}";
+    public static final String KEY_ID = "jiaokexinyong";
 }

+ 1 - 1
src/main/java/com/jkcredit/query/record/filter/RequestCheckFilter.java

@@ -18,7 +18,7 @@ import java.io.IOException;
  **/
 @WebFilter(urlPatterns = "/*", filterName = "requestCheckFilter")
 @Order(value = 1)
-@Component
+//@Component
 public class RequestCheckFilter implements Filter {
     @Autowired
     TokenService tokenService;

+ 16 - 2
src/main/java/com/jkcredit/query/record/service/impl/TokenServiceImpl.java

@@ -1,10 +1,16 @@
 package com.jkcredit.query.record.service.impl;
 
+import com.jkcredit.query.record.constant.CommonConstant;
 import com.jkcredit.query.record.service.TokenService;
 import com.jkcredit.query.record.util.JwtTokenUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.jose4j.json.JsonUtil;
+import org.jose4j.jwk.RsaJsonWebKey;
+import org.jose4j.lang.JoseException;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
+import java.security.PublicKey;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -13,6 +19,7 @@ import java.util.Map;
  * @version V1.0
  **/
 @Service
+@Slf4j
 public class TokenServiceImpl implements TokenService {
     @Value("${user.name}")
     private String userName;
@@ -28,12 +35,19 @@ public class TokenServiceImpl implements TokenService {
         Map<String, Object> claims = new HashMap<>();
         claims.put("client_key", clientKey);
         claims.put("client_secret", clientSecret);
-        return JwtTokenUtil.generateToken(userName, claims, 3600, userSalt);
+        return JwtTokenUtil.generateToken(userName, claims);
     }
 
     @Override
     public boolean validateToken(String token) {
-        String subject = JwtTokenUtil.parseToken(token, userSalt);
+        PublicKey publicKey;
+        try {
+            publicKey = new RsaJsonWebKey(JsonUtil.parseJson(CommonConstant.TOKEN_PUBLIC_KEY)).getPublicKey();
+        } catch (JoseException e) {
+            log.error("tokenParseException:", e);
+            return false;
+        }
+        String subject = JwtTokenUtil.parseToken(token, publicKey);
         if (subject != null && subject.equals(userName)) {
             return true;
         } else {

+ 35 - 39
src/main/java/com/jkcredit/query/record/util/JwtTokenUtil.java

@@ -1,64 +1,60 @@
 package com.jkcredit.query.record.util;
 
+import com.jkcredit.query.record.constant.CommonConstant;
 import io.jsonwebtoken.Claims;
 import io.jsonwebtoken.Jwts;
-import io.jsonwebtoken.SignatureAlgorithm;
+import org.jose4j.json.JsonUtil;
+import org.jose4j.jwk.RsaJsonWebKey;
+import org.jose4j.jws.AlgorithmIdentifiers;
+import org.jose4j.jws.JsonWebSignature;
+import org.jose4j.jwt.JwtClaims;
+import org.jose4j.jwt.NumericDate;
+import org.jose4j.lang.JoseException;
 
-import java.io.InputStream;
-import java.security.KeyStore;
 import java.security.PrivateKey;
 import java.security.PublicKey;
-import java.util.Date;
-import java.util.HashMap;
 import java.util.Map;
 
 public class JwtTokenUtil {
-
-    private static InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("jwt.jks"); // 寻找证书文件
-    private static PrivateKey privateKey = null;
-    private static PublicKey publicKey = null;
-    private static Map<String, Object> claims = new HashMap<>();
-
-    static { // 将证书文件里边的私钥公钥拿出来
+    public static String generateToken(String subject, Map<String, Object> user) {
+        JwtClaims claims = new JwtClaims();
+        claims.setGeneratedJwtId();
+        claims.setIssuedAtToNow();
+        //过期时间一定要设置,并且小于7天
+        NumericDate date = NumericDate.now();
+        date.addSeconds(60*60);
+        claims.setExpirationTime(date);
+        claims.setSubject(subject);
+        //添加自定义参数,所有值请都使用String类型
+        claims.setClaim("client_key", user.get("client_key"));
+        claims.setClaim("client_secret", user.get("client_secret"));
+
+        JsonWebSignature jws = new JsonWebSignature();
+        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
+        //必须设置
+        jws.setKeyIdHeaderValue(CommonConstant.KEY_ID);
+        jws.setPayload(claims.toJson());
+        String jwtResult = "";
         try {
-            KeyStore keyStore = KeyStore.getInstance("JKS"); // java key store 固定常量
-            keyStore.load(inputStream, "123456".toCharArray());
-//            privateKey = (PrivateKey) keyStore.getKey("jwt", "123456".toCharArray()); // jwt 为 命令生成整数文件时的别名
-//            publicKey = keyStore.getCertificate("jwt").getPublicKey();
-        } catch (Exception e) {
+            PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(CommonConstant.TOKEN_PRIVATE_KEY)).getPrivateKey();
+            jws.setKey(privateKey);
+            jwtResult = jws.getCompactSerialization();
+        } catch (JoseException e) {
             e.printStackTrace();
         }
-        claims.put("client_key", "deb7cf03360064d7");
-        claims.put("client_secret", "259ae98a84367d817aaf220b601b7f62");
-    }
-
-    public static String generateToken(String subject,Map<String, Object> claims, int expirationSeconds, String salt) {
-        return Jwts.builder()
-                .setClaims(claims)
-                .setSubject(subject)
-                .setExpiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000))
-                .signWith(SignatureAlgorithm.HS512, salt) // 不使用公钥私钥
-                .compact();
+        return jwtResult;
     }
 
-    public static String parseToken(String token, String salt) {
+    public static String parseToken(String token, PublicKey salt) {
         String subject = null;
         try {
             Claims claims = Jwts.parser()
-                    .setSigningKey(salt) // 不使用公钥私钥
+                    .setSigningKey(salt)
                     .parseClaimsJws(token).getBody();
             subject = claims.getSubject();
         } catch (Exception e) {
+            e.printStackTrace();
         }
         return subject;
     }
-
-    public static void main(String[] args) {
-        Map<String, Object> claims = new HashMap<>();
-        claims.put("client_key", "deb7cf03360064d7");
-        claims.put("client_secret", "259ae98a84367d817aaf220b601b7f62");
-
-        System.out.println(generateToken("sub", claims, 3000, "fhw4u543rth"));
-        System.out.println(parseToken("eyJhbGciOiJIUzUxMiJ9.eyJjbGllbnRfa2V5IjoiZGViN2NmMDMzNjAwNjRkNyIsInN1YiI6InN1YiIsImNsaWVudF9zZWNyZXQiOiIyNTlhZTk4YTg0MzY3ZDgxN2FhZjIyMGI2MDFiN2Y2MiIsImV4cCI6MTYyODUwNTQ3MH0.019SN9u2-0ZahHeguNWRGYwi5HxYQrzIScrP31vQci2FE7dekLg3dFM5Yn5Edzp-rLOnEHWffhiwvXJjf3F0VQ", "fhw4u543rth"));
-    }
 }