陈昶聿
23 小时以前 5a60b5408414926fd6fe6dbf39c958c749d31779
ruoyi-admin/src/main/java/com/ruoyi/web/controller/sso/SSOController.java
@@ -3,10 +3,13 @@
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.entity.SysUser;
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;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.smartor.domain.SSOTokenResponse;
import com.smartor.domain.SSOUserInfo;
@@ -17,17 +20,21 @@
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;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
@@ -80,6 +87,9 @@
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService sysConfigService;
    private final RestTemplate restTemplate;
    public SSOController() {
@@ -113,6 +123,58 @@
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * SSO登录入口 - 信通院会调用这个地址
     * 访问路径:http://域名:8095/sso/ssoLoginLyra
     */
    @GetMapping("ssoLoginLyra")
    public RedirectView ssoLoginLyra(@RequestParam(value = "code", required = false) String code) {
        log.info("收到SSOLyra登录请求,开始重定向到授权服务器,code = {}",code);
        String path = sysConfigService.selectConfigByKey("sys.qddz");
        String redirectUri = "https://9.208.2.190:8092/prod-api/sso/ssoLoginLyra";
        String lyraPath = "https://9.0.124.104:13021";
        String clientId = "1553588321874087936";
        String clientSecret = "suifangxt";
        String scope = "openid";
//        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();
        try {
            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 = "";
            reviewUrl = UriComponentsBuilder.fromHttpUrl(path)
                    .path("/loginSSO")
                    .queryParam("token", accessToken.getAccess_token())
                    .queryParam("orgid", userInfo.getZuZhiJGID())
                    .queryParam("orgname", userInfo.getZuZhiJGMC())
                    .queryParam("ZuHuID", userInfo.getYongHuID())
                    .queryParam("deptCode", "null")
                    .build()
                    .toUriString();
            log.info("单点登陆重定向地址为:{}", reviewUrl);
            redirectView.setUrl(reviewUrl);
            redirectView.setStatusCode(HttpStatus.FOUND);
        } catch (Exception e) {
            log.error("SSO登录失败", e);
            redirectView.setUrl(path + "/login?error=sso_failed");
            return redirectView;
        }
        return redirectView;
    }
    private Map<String, String> getResult(String param) {
@@ -195,6 +257,60 @@
    }
    /**
     * 获取访问令牌
     */
    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);
        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);
        log.info("getAccessTokenLyra: url = {}, params = {}" , accessTokenUrl, params);
        String result = OkHttpExample.postFormUnsafe(accessTokenUrl, params);
        log.info("Token响应: {}", result);
        if (result == null || result.trim().isEmpty()) {
            throw new RuntimeException("Token响应为空");
        }
        SSOTokenResponse tokenResponse = JSON.parseObject(result, SSOTokenResponse.class);
        if (tokenResponse == null || StringUtils.isEmpty(tokenResponse.getAccess_token())) {
            throw new RuntimeException("获取access_token失败");
        }
        return tokenResponse;
    }
    /**
     * 获取用户信息
     */
    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);
        if (result == null || result.trim().isEmpty()) {
            throw new RuntimeException("用户信息响应为空");
        }
        SSOUserInfo userInfo = JSON.parseObject(result, SSOUserInfo.class);
        if (userInfo == null || StringUtils.isEmpty(userInfo.getName())) {
            throw new RuntimeException("获取用户信息失败或用户名为空");
        }
        return userInfo;
    }
    /**
     * 创建本地会话
     */
    private String createLocalSession(SSOUserInfo userInfo) {