From 5a60b5408414926fd6fe6dbf39c958c749d31779 Mon Sep 17 00:00:00 2001
From: 陈昶聿 <chychen@nbjetron.com>
Date: 星期二, 17 三月 2026 16:38:33 +0800
Subject: [PATCH] 【丽水】ssoLoginLyra 接口对接调整 免SSL 登录

---
 ruoyi-admin/src/main/java/com/ruoyi/web/controller/sso/SSOController.java |   75 +++++++++---------------
 ruoyi-common/src/main/java/com/ruoyi/common/utils/OkHttpExample.java      |   99 +++++++++++++++++++++++++++++++++
 2 files changed, 127 insertions(+), 47 deletions(-)

diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/sso/SSOController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/sso/SSOController.java
index 0a74491..80f4e66 100644
--- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/sso/SSOController.java
+++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/sso/SSOController.java
@@ -5,6 +5,7 @@
 import com.ruoyi.common.core.domain.model.LoginUser;
 import com.ruoyi.common.exception.base.BaseException;
 import com.ruoyi.common.utils.HttpUtil;
+import com.ruoyi.common.utils.OkHttpExample;
 import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.common.utils.http.HttpUtils;
 import com.ruoyi.framework.web.service.TokenService;
@@ -19,6 +20,7 @@
 import org.springframework.http.client.SimpleClientHttpRequestFactory;
 import org.springframework.util.LinkedMultiValueMap;
 import org.springframework.util.MultiValueMap;
+import org.springframework.util.ObjectUtils;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestParam;
@@ -32,6 +34,7 @@
 import java.io.IOException;
 import java.net.URLEncoder;
 import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.Map;
 
 /**
@@ -127,45 +130,29 @@
      * 璁块棶璺緞锛歨ttp://鍩熷悕:8095/sso/ssoLoginLyra
      */
     @GetMapping("ssoLoginLyra")
-    public RedirectView ssoLoginLyra() {
-        log.info("鏀跺埌SSO鐧诲綍璇锋眰锛屽紑濮嬮噸瀹氬悜鍒版巿鏉冩湇鍔″櫒");
+    public RedirectView ssoLoginLyra(@RequestParam(value = "code", required = false) String code) {
+        log.info("鏀跺埌SSOLyra鐧诲綍璇锋眰锛屽紑濮嬮噸瀹氬悜鍒版巿鏉冩湇鍔″櫒,code = {}",code);
         String path = sysConfigService.selectConfigByKey("sys.qddz");
-//        String redirectUri = internalRedirectUri;
-        String redirectUri = "https://9.208.2.190:8092";
+        String redirectUri = "https://9.208.2.190:8092/prod-api/sso/ssoLoginLyra";
         String lyraPath = "https://9.0.124.104:13021";
-        String clientId = "1553548571532333056";
+        String clientId = "1553588321874087936";
         String clientSecret = "suifangxt";
         String scope = "openid";
 
-        String authorizeUrl = lyraPath + "/mediinfo-lyra-authserver/connect/authorize";
+//        String authorizeUrl = lyraPath + "/mediinfo-lyra-authserver/connect/authorize";
         String accessTokenUrl = lyraPath + "/mediinfo-lyra-authserver/connect/token";
         String userInfoUrl =  lyraPath + "/mediinfo-lyra-authserver/connect/userinfo";
         // 閲嶅畾鍚戝湴鍧�瀵硅薄(閲嶅畾鍚戝湴鍧�
         RedirectView redirectView = new RedirectView();
-
-        // Authorize閴存潈鎺ュ彛
-        String param = "client_id=" + clientId + "&redirect_uri=" + redirectUri + "&response_type=code" +
-                "&state=" + state + "&scope=" + scope;
-        log.info("銆怉uthorize閴存潈鎺ュ彛銆戝叆鍙備负锛歿}", param);
-//        String url = internalAuthorizeUrl;
-        String s = HttpUtils.sendGet(authorizeUrl, param);
-        Map<String, String> result = getResult(s);
-        String code = result.get("code");
-        if (StringUtils.isEmpty(code)) {
-            log.error("鏈幏鍙栧埌鎺堟潈鐮�");
-            throw new BaseException("SSO鎺堟潈澶辫触");
-        }
         try {
-            SSOTokenResponse accessToken = getAccessTokenLyra(code, accessTokenUrl, clientId, clientSecret,true);
+            SSOTokenResponse accessToken = getAccessTokenLyra(code, accessTokenUrl, clientId, redirectUri, clientSecret,true);
+            log.info("鑾峰彇鍒扮殑token锛�" + accessToken);
             SSOUserInfo userInfo = getUserInfoLyra(accessToken.getAccess_token(), userInfoUrl,true);
-
+            log.info("鑾峰彇鍒扮殑鐢ㄦ埛淇℃伅锛�" + userInfo);
             createLocalSession(userInfo);
             if (StringUtils.isEmpty(path)) {
                 throw new BaseException("璇烽厤缃墠绔湴鍧�");
             }
-//            String reviewUrl = path + "/loginSSO?token=" + accessToken.getAccess_token() + "&orgid=" +
-//                    userInfo.getZuZhiJGID() + "&orgname=" + userInfo.getZuZhiJGMC() +
-//                    "&ZuHuID="+ userInfo.getYongHuID() +"&deptCode=null";
             String reviewUrl = "";
             reviewUrl = UriComponentsBuilder.fromHttpUrl(path)
                     .path("/loginSSO")
@@ -272,29 +259,26 @@
     /**
      * 鑾峰彇璁块棶浠ょ墝
      */
-    private SSOTokenResponse getAccessTokenLyra(String code, String accessTokenUrl, String clientId, String clientSecret, boolean isInternal) throws Exception {
+    private SSOTokenResponse getAccessTokenLyra(String code, String accessTokenUrl, String clientId, String clientSecret, String redirectUri, boolean isInternal) throws Exception {
         HttpHeaders headers = new HttpHeaders();
         headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 
-        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
-        String redirectUri = getRedirectUri(isInternal);
-        params.add("client_id", clientId);
-        params.add("client_secret", clientSecret);
-        params.add("code", code);
-        params.add("grant_type", "authorization_code");
-        params.add("redirect_uri", redirectUri);
+        Map<String, String> params = new HashMap<>();
+        params.put("client_id", clientId);
+        params.put("client_secret", clientSecret);
+        params.put("code", code);
+        params.put("grant_type", "authorization_code");
+        params.put("redirect_uri", redirectUri);
 
-        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
+        log.info("getAccessTokenLyra: url = {}, params = {}" , accessTokenUrl, params);
+        String result = OkHttpExample.postFormUnsafe(accessTokenUrl, params);
+        log.info("Token鍝嶅簲: {}", result);
 
-        ResponseEntity<String> response = restTemplate.exchange(accessTokenUrl, HttpMethod.POST, request, String.class);
-
-        log.info("Token鍝嶅簲: {}", response.getBody());
-
-        if (response.getBody() == null || response.getBody().trim().isEmpty()) {
+        if (result == null || result.trim().isEmpty()) {
             throw new RuntimeException("Token鍝嶅簲涓虹┖");
         }
 
-        SSOTokenResponse tokenResponse = JSON.parseObject(response.getBody(), SSOTokenResponse.class);
+        SSOTokenResponse tokenResponse = JSON.parseObject(result, SSOTokenResponse.class);
 
         if (tokenResponse == null || StringUtils.isEmpty(tokenResponse.getAccess_token())) {
             throw new RuntimeException("鑾峰彇access_token澶辫触");
@@ -309,18 +293,15 @@
     private SSOUserInfo getUserInfoLyra(String accessToken, String userInfoUrl, boolean isInternal) throws Exception {
         HttpHeaders headers = new HttpHeaders();
         headers.set("Authorization", "Bearer " + accessToken);
+        log.info("getUserInfoLyra: url = {}, accessToken = {}" , userInfoUrl, accessToken);
+        String result = OkHttpExample.getUnsafe(userInfoUrl,accessToken);
+        log.info("鐢ㄦ埛淇℃伅鍝嶅簲: {}", result);
 
-        HttpEntity<String> entity = new HttpEntity<>(headers);
-
-        ResponseEntity<String> response = restTemplate.exchange(userInfoUrl, HttpMethod.GET, entity, String.class);
-
-        log.info("鐢ㄦ埛淇℃伅鍝嶅簲: {}", response.getBody());
-
-        if (response.getBody() == null || response.getBody().trim().isEmpty()) {
+        if (result == null || result.trim().isEmpty()) {
             throw new RuntimeException("鐢ㄦ埛淇℃伅鍝嶅簲涓虹┖");
         }
 
-        SSOUserInfo userInfo = JSON.parseObject(response.getBody(), SSOUserInfo.class);
+        SSOUserInfo userInfo = JSON.parseObject(result, SSOUserInfo.class);
 
         if (userInfo == null || StringUtils.isEmpty(userInfo.getName())) {
             throw new RuntimeException("鑾峰彇鐢ㄦ埛淇℃伅澶辫触鎴栫敤鎴峰悕涓虹┖");
diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/OkHttpExample.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/OkHttpExample.java
index 2cd917d..cec9085 100644
--- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/OkHttpExample.java
+++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/OkHttpExample.java
@@ -8,8 +8,17 @@
 import java.io.IOException;
 import java.security.SecureRandom;
 import java.security.cert.X509Certificate;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 public class OkHttpExample {
+    // 瀹氫箟 JSON 濯掍綋绫诲瀷
+    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
+    // 鍒涘缓 OkHttpClient 瀹炰緥锛堝叏灞�鍗曚緥鍗冲彲锛岄伩鍏嶉噸澶嶅垱寤猴級
+    private static final OkHttpClient client = new OkHttpClient.Builder()
+            .connectTimeout(5, TimeUnit.SECONDS)
+            .readTimeout(5, TimeUnit.SECONDS)
+            .build();
 
     public static OkHttpClient createUnsafeOkHttpClient() {
 
@@ -70,5 +79,95 @@
         }
     }
 
+    public static String sendGetRequestWithBearerToken(String url, String token) throws IOException {
+        // 鏋勫缓璇锋眰锛氭坊鍔� Authorization 璇锋眰澶达紙鏍煎紡锛欱earer + 绌烘牸 + token锛�
+        Request request = new Request.Builder()
+                .url(url)
+                .get() // GET 璇锋眰锛堝彲鐪佺暐锛岄粯璁ゅ氨鏄� GET锛�
+                .addHeader("Authorization", "Bearer " + token) // 鏍稿績锛欱earer Token 澶�
+                .addHeader("Content-Type", "application/json") // 鎸夐渶娣诲姞鍏朵粬澶�
+                .build();
+
+        // 鎵ц璇锋眰骞惰繑鍥炲搷搴�
+        try (Response response = client.newCall(request).execute()) {
+            if (!response.isSuccessful()) {
+                throw new IOException("璇锋眰澶辫触锛屽搷搴旂爜锛�" + response.code() + "锛屾秷鎭細" + response.message());
+            }
+            // 璇诲彇鍝嶅簲浣擄紙string() 浼氳嚜鍔ㄥ叧闂祦锛屾棤闇�鎵嬪姩鍏筹級
+            return response.body().string();
+        }
+    }
+
+    // GET 璇锋眰鏂规硶
+    public static String get(String url) throws IOException {
+        Request request = new Request.Builder()
+                .url(url)
+                .get() // 榛樿涓� GET锛屽彲鐪佺暐
+                .build();
+
+        // 鎵ц璇锋眰骞惰幏鍙栧搷搴�
+        try (Response response = client.newCall(request).execute()) {
+            if (!response.isSuccessful()) {
+                throw new IOException("GET 璇锋眰澶辫触锛�" + response);
+            }
+            return response.body().string(); // 璇诲彇鍝嶅簲浣�
+        }
+    }
+
+    // POST 璇锋眰鏂规硶锛堟惡甯� JSON 鍙傛暟锛�
+    public static String post(String url, String json) throws IOException {
+        RequestBody body = RequestBody.create(JSON, json);
+        Request request = new Request.Builder()
+                .url(url)
+                .post(body)
+                .build();
+
+        try (Response response = client.newCall(request).execute()) {
+            if (!response.isSuccessful()) {
+                throw new IOException("POST 璇锋眰澶辫触锛�" + response);
+            }
+            return response.body().string();
+        }
+    }
+
+    // POST 璇锋眰鏂规硶锛坒orm-urlencoded + 蹇界暐SSL璇佷功锛岄�傜敤浜嶰Auth2 token绔偣锛�
+    public static String postFormUnsafe(String url, Map<String, String> formParams) throws IOException {
+        OkHttpClient unsafeClient = createUnsafeOkHttpClient();
+
+        FormBody.Builder formBuilder = new FormBody.Builder();
+        for (Map.Entry<String, String> entry : formParams.entrySet()) {
+            formBuilder.add(entry.getKey(), entry.getValue());
+        }
+
+        Request request = new Request.Builder()
+                .url(url)
+                .post(formBuilder.build())
+                .build();
+
+        try (Response response = unsafeClient.newCall(request).execute()) {
+            if (!response.isSuccessful()) {
+                throw new IOException("POST form 璇锋眰澶辫触锛�" + response.code() + " " + response.message());
+            }
+            return response.body().string();
+        }
+    }
+
+    // GET 璇锋眰鏂规硶锛堝弬鏁版嫾鎺ュ埌URL + 蹇界暐SSL璇佷功锛岄�傜敤浜嶰Auth2 token绔偣锛�
+    public static String getUnsafe(String url, String token) throws IOException {
+        OkHttpClient unsafeClient = createUnsafeOkHttpClient();
+
+        Request request = new Request.Builder()
+                .url(url)
+                .addHeader("Authorization", "Bearer " + token) // 鏍稿績锛欱earer Token 澶�
+                .get()
+                .build();
+
+        try (Response response = unsafeClient.newCall(request).execute()) {
+            if (!response.isSuccessful()) {
+                throw new IOException("GET form 璇锋眰澶辫触锛�" + response.code() + " " + response.message());
+            }
+            return response.body().string();
+        }
+    }
 
 }

--
Gitblit v1.9.3