Jelajahi Sumber

认证服务代码整理,加注释

nnkwrik 6 tahun lalu
induk
melakukan
8ceaaf8218

+ 1 - 1
auth-service/src/main/java/io/github/nnkwrik/authservice/config/WxMaConfiguration.java

@@ -33,7 +33,7 @@ public class WxMaConfiguration {
     @Bean
     public Object services() {
         WxMaInMemoryConfig config = new WxMaInMemoryConfig();
-        BeanUtils.copyProperties(properties,config);
+        BeanUtils.copyProperties(properties, config);
         maServices = new WxMaServiceImpl();
         maServices.setWxMaConfig(config);
 

+ 14 - 34
auth-service/src/main/java/io/github/nnkwrik/authservice/controller/AuthController.java

@@ -2,8 +2,6 @@ package io.github.nnkwrik.authservice.controller;
 
 import cn.binarywang.wx.miniapp.api.WxMaUserService;
 import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
 import io.github.nnkwrik.authservice.config.WxMaConfiguration;
 import io.github.nnkwrik.authservice.dto.AuthDTO;
 import io.github.nnkwrik.authservice.dto.DetailAuthDTO;
@@ -11,15 +9,13 @@ import io.github.nnkwrik.authservice.model.vo.AuthVo;
 import io.github.nnkwrik.authservice.mq.RegisterStreamSender;
 import io.github.nnkwrik.authservice.service.AuthService;
 import io.github.nnkwrik.common.dto.Response;
-import io.github.nnkwrik.common.mq.UserRegisterStream;
 import lombok.extern.slf4j.Slf4j;
 import me.chanjar.weixin.common.error.WxErrorException;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.cloud.stream.annotation.EnableBinding;
-import org.springframework.util.StringUtils;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.Map;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
 
 /**
  * @author nnkwrik
@@ -27,7 +23,6 @@ import java.util.Map;
  */
 @Slf4j
 @RestController
-@EnableBinding(UserRegisterStream.class)
 @RequestMapping("/auth")
 public class AuthController {
 
@@ -39,14 +34,20 @@ public class AuthController {
     @Autowired
     private RegisterStreamSender registerSender;
 
-
+    /**
+     * 微信后台登录
+     *
+     * @param authDTO code : jsCode(通过wx.login()获取)
+     *                detail : userInfo(通过open-type="getUserInfo"或wx.wx.getUserInfo()获取)
+     * @return JWT Token和自定义的userInfo
+     */
     @PostMapping("/loginByWeixin")
-    public Response loginByWeixin(@RequestBody AuthDTO authDTO) {
+    public Response<AuthVo> loginByWeixin(@RequestBody AuthDTO authDTO) {
 
         log.info("用户登录 : {}", authDTO);
         WxMaUserService wxUserService = WxMaConfiguration.getMaServices().getUserService();
 
-        //验证用户登录凭证
+        //验证jscode
         WxMaJscode2SessionResult sessionInfo = null;
         try {
             sessionInfo = wxUserService.getSessionInfo(authDTO.getCode());
@@ -66,8 +67,8 @@ public class AuthController {
             return Response.fail(Response.CHECK_USER_WITH_SESSION_FAIL, message);
         }
 
+        //异步消息调用user-service注册到数据库
         String userData = authService.setOpenId4Data(detail.getRawData(), openId);
-        //异步调用user-service注册到数据库
         registerSender.send(userData);
 
         //构造JWT token
@@ -77,26 +78,5 @@ public class AuthController {
         return Response.ok(vo);
     }
 
-    /**
-     * 测试环境专用
-     *
-     * @param
-     * @return
-     */
-    @PostMapping("/loginByWeixinDev")
-    public Response loginByWeixinDev(@RequestBody Map<String, String> jsonMap, @RequestHeader("Authorization") String token) throws JsonProcessingException {
-        log.info("用户登录 : {}", "测试");
-//        JsonUtil.fromJson()
-        ObjectMapper mapper = new ObjectMapper();
-        String userData = mapper.writeValueAsString(jsonMap);
-
-        //异步调用user-service注册到数据库
-        registerSender.send(userData);
-
-        AuthVo vo = authService.createToken(userData);
-        return Response.ok(vo);
-
-    }
-
 
 }

+ 1 - 1
auth-service/src/main/java/io/github/nnkwrik/authservice/mq/RegisterStreamSender.java

@@ -20,7 +20,7 @@ public class RegisterStreamSender {
     private UserRegisterStream streamClient;
 
     public void send(String userDate) {
-        log.info("向【用户服务】发起【用户注册】的消息,消息内容:{}",userDate);
+        log.info("向【用户服务】发起【用户注册】的消息,消息内容:{}", userDate);
         streamClient.output().send(MessageBuilder.withPayload(userDate).build());
     }
 }

+ 0 - 2
auth-service/src/main/java/io/github/nnkwrik/authservice/service/AuthService.java

@@ -11,6 +11,4 @@ public interface AuthService {
 
     AuthVo createToken(String userData);
 
-//    boolean isExpiredToken(String token, String loginOpenId);
-
 }

+ 0 - 46
auth-service/src/main/java/io/github/nnkwrik/authservice/service/impl/AuthServiceImpl.java

@@ -1,6 +1,5 @@
 package io.github.nnkwrik.authservice.service.impl;
 
-import com.auth0.jwt.exceptions.TokenExpiredException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import io.github.nnkwrik.authservice.model.vo.AuthVo;
@@ -14,7 +13,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.io.IOException;
-import java.util.Base64;
 import java.util.Map;
 
 /**
@@ -79,49 +77,5 @@ public class AuthServiceImpl implements AuthService {
         }
         return new AuthVo(token, jwtUser);
     }
-//
-//    /**
-//     * 确认是否是内容正确但过期的token
-//     * @param token 从客户端传来的token
-//     * @param loginOpenId 本次登录获取到的openId
-//     * @return
-//     */
-//    @Override
-//    public boolean isExpiredToken(String token, String loginOpenId) {
-//        try {
-//            JWTUser jwtUser = tokenSolver.solve(token);
-//            log.info("token没有失效,有效的jwt");
-//            return isSameOpenId(jwtUser.getOpenId(), loginOpenId);
-//
-//        } catch (TokenExpiredException e) {
-//            log.info("过期的jwt,过期时间:{}", e.getMessage());
-//            String openIdFromToken = getOpenIdFromToken(token);
-//            return isSameOpenId(openIdFromToken, loginOpenId);
-//
-//        } catch (Exception e) {
-//            log.info("jwt解析失败");
-//        }
-//        return false;
-//    }
-//
-//
-//    private String getOpenIdFromToken(String token) {
-//        Base64.Decoder decoder = Base64.getUrlDecoder();
-//        token = token.replace("Bearer ", "");
-//        String[] parts = token.split("\\.");
-//        String payload = new String(decoder.decode(parts[1]));
-//        Map<String, String> json = JsonUtil.fromJson(payload, JsonUtil.simpleJsonMap);
-//        return json.get("openId");
-//
-//    }
-//
-//    private boolean isSameOpenId(String oldId, String newId) {
-//        if (oldId.equals(newId)) {
-//            return true;
-//        }
-//        log.info("过期的jwt中的openid和本次注册的openid不同。过期的openid={},本次注册的openId={}", oldId, newId);
-//        return false;
-//    }
-
 
 }

+ 4 - 1
auth-service/src/main/java/io/github/nnkwrik/authservice/token/RSAKeysGenerator.java

@@ -12,6 +12,7 @@ import java.util.Base64;
 /**
  * 生成rsa的公钥和私钥
  * 需要把生成的公钥(.pub)拷贝到需要使用jwt的所有模块的resources目录下
+ *
  * @author nnkwrik
  * @date 18/11/12 11:35
  */
@@ -27,6 +28,7 @@ public class RSAKeysGenerator {
     }
 
     public static void generateRSAKeys(String location, String filePrefix) {
+        //生成RSA对
         KeyPairGenerator kpg = null;
         try {
             kpg = KeyPairGenerator.getInstance("RSA");
@@ -44,6 +46,7 @@ public class RSAKeysGenerator {
 
         Writer out = null;
         try {
+            //输出RSA私钥
             if (outFile != null) out = new FileWriter(outFile + ".key");
             else out = new OutputStreamWriter(System.out);
 
@@ -53,6 +56,7 @@ public class RSAKeysGenerator {
             out.write(encoder.encodeToString(pvt.getEncoded()));
             out.write("\n-----END RSA PRIVATE KEY-----\n");
 
+            //输出RSA公钥
             if (outFile != null) {
                 out.close();
                 out = new FileWriter(outFile + ".pub");
@@ -79,7 +83,6 @@ public class RSAKeysGenerator {
     }
 
 
-
     public static void main(String[] args) {
         generateRSAKeys();
     }

+ 13 - 4
auth-service/src/main/java/io/github/nnkwrik/authservice/token/TokenCreator.java

@@ -6,15 +6,14 @@ import com.auth0.jwt.algorithms.Algorithm;
 import com.auth0.jwt.interfaces.RSAKeyProvider;
 import io.github.nnkwrik.common.dto.JWTUser;
 import io.github.nnkwrik.common.token.RSAKeysReader;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
 import java.lang.reflect.Field;
 import java.security.interfaces.RSAPrivateKey;
 import java.security.interfaces.RSAPublicKey;
+import java.time.Duration;
 import java.time.Instant;
-import java.time.temporal.ChronoUnit;
 import java.util.Date;
 
 
@@ -28,6 +27,9 @@ public class TokenCreator {
     @Value("${jwt.pvt-key-file-name}")
     private String pvtFile;
 
+    @Value("${jwt.duration}")
+    private Duration duration;
+
     public RSAKeyProvider keyProvider = new RSAKeyProvider() {
 
         RSAPrivateKey key;
@@ -49,10 +51,17 @@ public class TokenCreator {
         }
     };
 
+    /**
+     * 构造JWT Token
+     *
+     * @param jwtUser
+     * @return
+     * @throws IllegalAccessException
+     */
     public String create(JWTUser jwtUser) throws IllegalAccessException {
         Algorithm algorithm = Algorithm.RSA256(keyProvider);
-        //一天后过期
-        Date expire = Date.from(Instant.now().plus(1, ChronoUnit.DAYS));
+
+        Date expire = Date.from(Instant.now().plus(duration));
 
         JWTCreator.Builder builder = JWT.create();
 

+ 8 - 1
auth-service/src/main/resources/application.yml

@@ -21,12 +21,19 @@ spring:
           destination: register
           content-type: application/json
 
-
 server:
   port: 8803
 
+#写入你的小程序信息
+wx:
+  miniapp:
+    appid:  #微信小程序的appid
+    secret: #微信小程序的Secret
+    msgDataFormat: JSON
+
 jwt:
   pvt-key-file-name: RSA.key
   pub-key-file-name: RSA.pub
+  duration: 1D  #JWT 1天过期
 
 

+ 3 - 0
zuul/src/main/resources/application.yml

@@ -8,6 +8,9 @@ spring:
   application:
     name: api-gateway
 zuul:
+  ribbon:
+    ReadTimeout: 60000
+    ConnectTimeout: 60000
   routes:
     #auth-service
     auth: