fanxp 1 year ago
parent
commit
87f41534c2

+ 2 - 2
pom.xml

@@ -24,7 +24,7 @@
         <commons.codec.version>1.10</commons.codec.version>
         <commons.configuration.version>1.10</commons.configuration.version>
         <hutool.version>5.7.20</hutool.version>
-        <satoken.version>1.29.0</satoken.version>
+        <satoken.version>1.35.0.RC</satoken.version>
         <lombok.version>1.18.4</lombok.version>
         <fastjson.version>1.2.83</fastjson.version>
         <joda.time.version>2.9.9</joda.time.version>
@@ -144,7 +144,7 @@
         <!-- Sa-Token 整合 Redis (使用jdk默认序列化方式) -->
         <dependency>
             <groupId>cn.dev33</groupId>
-            <artifactId>sa-token-dao-redis</artifactId>
+            <artifactId>sa-token-redis</artifactId>
             <version>${satoken.version}</version>
         </dependency>
 

+ 6 - 0
src/main/java/com/xjrsoft/common/constant/GlobalConstant.java

@@ -489,4 +489,10 @@ public interface GlobalConstant {
      * mqtt 请求参数前缀
      */
     String MQTT_REQUEST_ID =  "mqttrequestid:";
+
+
+    /**
+     * oauth2 缓存key
+     */
+    String OAUTH2  = "oauth2:";
 }

+ 10 - 0
src/main/java/com/xjrsoft/config/CommonPropertiesConfig.java

@@ -21,6 +21,16 @@ public class CommonPropertiesConfig {
 
     private String defaultPassword;
 
+    /**
+     * api域名地址
+     */
+    private String domainApi;
+
+    /**
+     * web域名地址
+     */
+    private String domainWeb;
+
     private List<String> excludeUrls;
 
     private List<String> whiteList;

+ 2 - 3
src/main/java/com/xjrsoft/config/SaTokenConfig.java

@@ -1,12 +1,11 @@
 package com.xjrsoft.config;
 
 import cn.dev33.satoken.context.SaHolder;
-import cn.dev33.satoken.exception.DisableLoginException;
+import cn.dev33.satoken.exception.DisableServiceException;
 import cn.dev33.satoken.exception.NotLoginException;
 import cn.dev33.satoken.exception.NotPermissionException;
 import cn.dev33.satoken.exception.NotRoleException;
 import cn.dev33.satoken.filter.SaServletFilter;
-import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
 import cn.dev33.satoken.router.SaHttpMethod;
 import cn.dev33.satoken.router.SaRouter;
 import cn.dev33.satoken.stp.StpUtil;
@@ -92,7 +91,7 @@ public class SaTokenConfig implements WebMvcConfigurer {
                         return SaResult.get(ResponseCode.REQ_REJECT.getCode(), ResponseCode.REQ_REJECT.getMessage(), null);
                     } else if (e instanceof NotPermissionException) {    // 如果是权限异常
                         return SaResult.get(ResponseCode.REQ_REJECT.getCode(), ResponseCode.REQ_REJECT.getMessage(), null);
-                    } else if (e instanceof DisableLoginException) {    // 如果是被封禁异常
+                    } else if (e instanceof DisableServiceException) {    // 如果是被封禁异常
                         return SaResult.get(ResponseCode.REQ_REJECT.getCode(), ResponseCode.REQ_REJECT.getMessage(), null);
                     } else {    // 普通异常, 输出:500 + 异常信息
                         return SaResult.get(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), ResponseCode.INTERNAL_SERVER_ERROR.getMessage(), null);

+ 32 - 15
src/main/java/com/xjrsoft/module/system/controller/Oauth2Controller.java

@@ -1,14 +1,20 @@
 package com.xjrsoft.module.system.controller;
 
+import cn.dev33.satoken.config.SaCookieConfig;
 import cn.dev33.satoken.context.SaHolder;
+import cn.dev33.satoken.context.model.SaCookie;
 import cn.dev33.satoken.context.model.SaRequest;
 import cn.dev33.satoken.context.model.SaResponse;
 import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
 import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
+import cn.dev33.satoken.stp.StpLogic;
 import cn.dev33.satoken.stp.StpUtil;
 import cn.dev33.satoken.util.SaResult;
+import cn.hutool.core.util.IdUtil;
 import com.xjrsoft.common.annotation.XjrLog;
 import com.xjrsoft.common.constant.GlobalConstant;
+import com.xjrsoft.common.utils.RedisUtil;
+import com.xjrsoft.config.CommonPropertiesConfig;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.AllArgsConstructor;
@@ -17,6 +23,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.servlet.ModelAndView;
 
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -28,13 +36,16 @@ import java.util.Map;
 @AllArgsConstructor
 public class Oauth2Controller {
 
+    @Autowired
+    private CommonPropertiesConfig commonPropertiesConfig;
+
+    private final RedisUtil redisUtil;
+
     // 处理所有OAuth相关请求
     @RequestMapping("/oauth2/*")
     @ApiOperation(value = "oauth2", notes = "处理所有OAuth相关请求")
     @XjrLog(value = "处理所有OAuth相关请求")
     public Object request() {
-        System.out.println("------- 进入请求: " + SaHolder.getRequest().getUrl());
-
         return SaOAuth2Handle.serverRequest();
     }
 
@@ -44,20 +55,26 @@ public class Oauth2Controller {
         // 配置:未登录时返回的View
         cfg.setNotLoginView(() -> {
                     SaRequest req = SaHolder.getRequest();
-//                    Map<String, String> paramMap = req.getp
-//                    StringBuilder param = new StringBuilder();
-//                    paramMap.forEach((k, v) -> {
-//                        param.append("&").append(k).append("=").append(v);
-//                    });
-//                    param.deleteCharAt(0);
+                    Map<String, String> paramMap = req.getParamMap();
+                    StringBuilder param = new StringBuilder();
+                    paramMap.forEach((k, v) -> {
+                        param.append("&").append(k).append("=").append(v);
+                    });
+                    param.deleteCharAt(0);
+                    String callBackUrl = String.format("%s?%s", req.getUrl(), param);
+
+                    String key = GlobalConstant.OAUTH2 + IdUtil.simpleUUID();
+                    redisUtil.set(key, callBackUrl, 86400);
+
                     SaResponse res = SaHolder.getResponse();
-                    res.redirect("http://127.0.0.1:9000/#/login");
+                    SaCookie cookie = new SaCookie()
+                            .setName("Oauth2Info")
+                            .setValue(key);
+
+                    res.addCookie(cookie);
+
+                    res.redirect(String.format("%s/#/login", commonPropertiesConfig.getDomainWeb()));
                     return null;
-//                    return new ModelAndView("login.html");
-//                    String msg = "当前会话在OAuth-Server端尚未登录,请先访问"
-//                        + "<a href='/oauth2/doLogin?name=sa&pwd=123456' target='_blank'> doLogin登录 </a>"
-//                        + "进行登录之后,刷新页面开始授权";
-//                return msg;
                 }).
                 // 配置:登录处理函数
                 setDoLoginHandle((name, pwd) -> {
@@ -68,7 +85,7 @@ public class Oauth2Controller {
                     return SaResult.error("账号名或密码错误");
                 }).
                 // 配置:确认授权时返回的View
-                    setConfirmView((clientId, scope) -> {
+                setConfirmView((clientId, scope) -> {
                     Map<String, Object> map = new HashMap<>();
                     map.put("clientId", clientId);
                     map.put("scope", scope);

+ 20 - 4
src/main/java/com/xjrsoft/module/system/service/impl/LoginServiceImpl.java

@@ -1,5 +1,8 @@
 package com.xjrsoft.module.system.service.impl;
 
+import cn.dev33.satoken.context.SaHolder;
+import cn.dev33.satoken.oauth2.SaOAuth2Manager;
+import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
 import cn.dev33.satoken.secure.BCrypt;
 import cn.dev33.satoken.session.SaSession;
 import cn.dev33.satoken.stp.StpUtil;
@@ -20,6 +23,7 @@ import com.xjrsoft.common.utils.FixedArithmeticCaptcha;
 import com.xjrsoft.common.utils.RSAUtil;
 import com.xjrsoft.common.utils.RedisUtil;
 import com.xjrsoft.common.utils.WeChatUtil;
+import com.xjrsoft.config.CommonPropertiesConfig;
 import com.xjrsoft.config.LicenseConfig;
 import com.xjrsoft.module.organization.entity.*;
 import com.xjrsoft.module.organization.mapper.UserRoleRelationMapper;
@@ -35,6 +39,7 @@ import com.xjrsoft.module.system.vo.LoginByCodeVo;
 import com.xjrsoft.module.system.vo.LoginVo;
 import lombok.AllArgsConstructor;
 import org.jetbrains.annotations.NotNull;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.util.List;
@@ -61,18 +66,20 @@ public class LoginServiceImpl implements ILoginService {
 
     private final RedisUtil redisUtil;
 
-
     private final LicenseConfig licenseConfig;
 
     private final WeChatUtil weChatUtil;
 
     private final UserRoleRelationMapper userRoleRelationMapper;
 
+    @Autowired
+    private CommonPropertiesConfig commonPropertiesConfig;
+
     @Override
     public LoginVo login(LoginDto dto) throws Exception {
         if (licenseConfig.getEnabled()) {
             //查出所有在线用户
-            List<String> onlineUser = StpUtil.searchSessionId("", 0, Integer.MAX_VALUE);
+            List<String> onlineUser = StpUtil.searchSessionId("", 0,-1, true);
 
             //如果已经登录人数超过授权人数  不允许登录
             if (onlineUser.size() >= licenseConfig.getLoginMax()) {
@@ -128,6 +135,7 @@ public class LoginServiceImpl implements ILoginService {
 
     /**
      * 手机验证码登录
+     *
      * @param dto
      * @return
      * @throws Exception
@@ -245,15 +253,23 @@ public class LoginServiceImpl implements ILoginService {
         tokenSession.set(GlobalConstant.LOGIN_USER_INFO_KEY, loginUser);
 
         result.setToken(StpUtil.getTokenValue());
+
+        // 判断是不是OAuth2
+        String oauth2Info = SaHolder.getRequest().getCookieValue("Oauth2Info");
+        if (oauth2Info != null) {
+            result.setRedirectUri(redisUtil.get(oauth2Info));
+        }
+
         return result;
     }
 
     /**
      * 角色匹配
+     *
      * @return
      */
-    private Long roleMatching(List<UserRoleRelation> relations){
-        for (UserRoleRelation role :relations) {
+    private Long roleMatching(List<UserRoleRelation> relations) {
+        for (UserRoleRelation role : relations) {
             if (role.getRoleId() == RoleEnum.PARENT.getCode()) {
                 return RoleEnum.PARENT.getCode();
             }

+ 5 - 0
src/main/java/com/xjrsoft/module/system/vo/LoginVo.java

@@ -18,4 +18,9 @@ public class LoginVo {
      * 用户类型 0=未匹配 1=超级管理员 2=教师 3=学生 4=家长
      */
     private Long userType;
+
+    /**
+     * 跳转地址
+     */
+    private String redirectUri;
 }

+ 4 - 1
src/main/resources/application-dev.yml

@@ -15,7 +15,7 @@ spring:
 
 
   redis:
-    database: 10
+    database: 11
     host: 8.142.26.206
     port: 6379
     password: wa3re~86Hu&ifniyM   # 密码(默认为空)
@@ -60,6 +60,9 @@ xjrsoft:
     druid-account: admin # druid 监控账户
     druid-password: admin # druid 监控密码
     default-password: "000000" #默认密码(用户重置密码后为该密码)
+    domain-api: https://test.tl.web.yingcaibx.com/api #api域名地址
+    domain-web: https://test.tl.web.yingcaibx.com #web域名地址
+#    domain-web: http://127.0.0.1:9000 #web域名地址
     white-list:
       - 192.168.0.139
     exclude-urls:

+ 2 - 1
src/main/resources/magic-editor-config.js

@@ -10,7 +10,8 @@ var MAGIC_EDITOR_CONFIG = {
     request: {
         beforeSend: function (config) {
             // console.log('请求设置', window.location.href);
-            config.headers.Authorization = "Bearer " + window.location.href.split('Authorization=')[1];
+            // config.headers.Authorization = "Bearer " + window.location.href.split('Authorization=')[1];
+            config.headers.Authorization = window.location.href.split('Authorization=')[1];
             return config;
         },
         onError: function (err) {