陈昶聿
23 小时以前 5a60b5408414926fd6fe6dbf39c958c749d31779
【丽水】ssoLoginLyra 接口对接调整 免SSL 登录
已修改2个文件
174 ■■■■ 文件已修改
ruoyi-admin/src/main/java/com/ruoyi/web/controller/sso/SSOController.java 75 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-common/src/main/java/com/ruoyi/common/utils/OkHttpExample.java 99 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
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 @@
     * 访问路径:http://域名: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("【Authorize鉴权接口】入参为:{}", 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("获取用户信息失败或用户名为空");
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 请求头(格式:Bearer + 空格 + token)
        Request request = new Request.Builder()
                .url(url)
                .get() // GET 请求(可省略,默认就是 GET)
                .addHeader("Authorization", "Bearer " + token) // 核心:Bearer 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 请求方法(form-urlencoded + 忽略SSL证书,适用于OAuth2 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证书,适用于OAuth2 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) // 核心:Bearer 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();
        }
    }
}