liusheng
2025-08-09 44d70e42817bfb518f29240d396ee3f53297e9fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package com.ruoyi.web.controller.sso;
 
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.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import com.smartor.domain.SSOTokenResponse;
import com.smartor.domain.SSOUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
 
/**
 * SSO单点登录控制器
 */
@RestController
@RequestMapping("/sso")
@Slf4j
public class SSOController {
 
    @Value("${sso.client_id}")
    private String clientId;
 
    @Value("${sso.client_secret}")
    private String clientSecret;
 
    @Value("${sso.internal.authorize_url}")
    private String internalAuthorizeUrl;
 
    @Value("${sso.internal.token_url}")
    private String internalTokenUrl;
 
    @Value("${sso.internal.userinfo_url}")
    private String internalUserinfoUrl;
 
    @Value("${sso.internal.redirect_uri}")
    private String internalRedirectUri;
 
    @Value("${sso.external.authorize_url}")
    private String externalAuthorizeUrl;
 
    @Value("${sso.external.token_url}")
    private String externalTokenUrl;
 
    @Value("${sso.external.userinfo_url}")
    private String externalUserinfoUrl;
 
    @Value("${sso.external.redirect_uri}")
    private String externalRedirectUri;
 
    @Value("${sso.state}")
    private String state;
 
    @Value("${sso.scope}")
    private String scope;
 
    @Autowired
    private ISysUserService userService;
 
    @Autowired
    private TokenService tokenService;
 
    private final RestTemplate restTemplate;
 
    public SSOController() {
        // 配置RestTemplate超时
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(10000); // 连接超时10秒
        factory.setReadTimeout(30000);    // 读取超时30秒
        this.restTemplate = new RestTemplate(factory);
    }
 
    /**
     * SSO登录入口 - 信通院会调用这个地址
     * 访问路径:http://域名:8095/sso/login
     */
    @GetMapping("")
    public void ssoLogin(HttpServletResponse response, HttpServletRequest request) throws IOException {
        log.info("收到SSO登录请求,开始重定向到授权服务器");
 
        // 获取客户端IP
        String clientIp = getClientIp(request);
        boolean isInternal = isInternalNetwork(clientIp);
 
        // 构建授权URL
        String authUrl = buildAuthorizationUrl(isInternal);
        log.info("重定向到授权URL: {}", authUrl);
 
        response.sendRedirect(authUrl);
    }
 
    /**
     * SSO回调处理
     */
    @GetMapping("/callback")
    public void ssoCallback(@RequestParam(required = false) String code,
                           @RequestParam(required = false) String state,
                           @RequestParam(required = false) String error,
                           HttpServletResponse response,
                           HttpServletRequest request) throws IOException {
 
        log.info("收到SSO回调,code: {}, state: {}, error: {}", code, state, error);
 
        if (error != null) {
            log.error("SSO授权失败: {}", error);
            try {
                response.sendRedirect("/login?sso_error=" + URLEncoder.encode(error, "UTF-8"));
            } catch (Exception e) {
                log.error("重定向失败", e);
                response.sendRedirect("/login?sso_error=unknown_error");
            }
            return;
        }
 
        if (code == null || !this.state.equals(state)) {
            log.error("SSO回调参数错误,code: {}, state: {}", code, state);
            response.sendRedirect("/login?sso_error=invalid_callback");
            return;
        }
 
        try {
            // 获取客户端IP
            String clientIp = getClientIp(request);
            boolean isInternal = isInternalNetwork(clientIp);
 
            // 1. 用code换取access_token
            SSOTokenResponse tokenResponse = getAccessToken(code, isInternal);
            log.info("获取到access_token: {}", tokenResponse.getAccess_token());
 
            // 2. 用access_token获取用户信息
            SSOUserInfo userInfo = getUserInfo(tokenResponse.getAccess_token(), isInternal);
            log.info("获取到用户信息: {}", userInfo);
 
            // 3. 根据用户信息创建本地会话
            String token = createLocalSession(userInfo);
 
            // 4. 重定向到前端首页,携带token
            String frontendUrl = "/#/index?token=" + token;
            response.sendRedirect(frontendUrl);
 
        } catch (RuntimeException e) {
            log.error("SSO业务处理失败: {}", e.getMessage(), e);
            try {
                response.sendRedirect("/login?sso_error=" + URLEncoder.encode(e.getMessage(), "UTF-8"));
            } catch (Exception ex) {
                log.error("重定向失败", ex);
                response.sendRedirect("/login?sso_error=system_error");
            }
        } catch (Exception e) {
            log.error("SSO登录处理失败", e);
            response.sendRedirect("/login?sso_error=login_failed");
        }
    }
 
    /**
     * 构建授权URL
     */
    private String buildAuthorizationUrl(boolean isInternal) {
        try {
            String redirectUri = getRedirectUri(isInternal);
            return getAuthorizeUrl(isInternal) + "?" +
                    "client_id=" + clientId +
                    "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8") +
                    "&response_type=code" +
                    "&state=" + state +
                    "&scope=" + URLEncoder.encode(scope, "UTF-8");
        } catch (Exception e) {
            log.error("构建授权URL失败", e);
            throw new RuntimeException("构建授权URL失败", e);
        }
    }
 
    /**
     * 获取访问令牌
     */
    private SSOTokenResponse getAccessToken(String code, boolean isInternal) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("client_id", clientId);
        params.add("client_secret", clientSecret);
        params.add("code", code);
        params.add("grant_type", "authorization_code");
        params.add("redirect_uri", getRedirectUri(isInternal));
 
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
 
        ResponseEntity<String> response = restTemplate.exchange(
                getTokenUrl(isInternal), HttpMethod.POST, request, String.class);
 
        log.info("Token响应: {}", response.getBody());
 
        if (response.getBody() == null || response.getBody().trim().isEmpty()) {
            throw new RuntimeException("Token响应为空");
        }
 
        SSOTokenResponse tokenResponse = JSON.parseObject(response.getBody(), SSOTokenResponse.class);
 
        if (tokenResponse == null || StringUtils.isEmpty(tokenResponse.getAccess_token())) {
            throw new RuntimeException("获取access_token失败");
        }
 
        return tokenResponse;
    }
 
    /**
     * 获取用户信息
     */
    private SSOUserInfo getUserInfo(String accessToken, boolean isInternal) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + accessToken);
 
        HttpEntity<String> entity = new HttpEntity<>(headers);
 
        ResponseEntity<String> response = restTemplate.exchange(
                getUserinfoUrl(isInternal), HttpMethod.GET, entity, String.class);
 
        log.info("用户信息响应: {}", response.getBody());
 
        if (response.getBody() == null || response.getBody().trim().isEmpty()) {
            throw new RuntimeException("用户信息响应为空");
        }
 
        SSOUserInfo userInfo = JSON.parseObject(response.getBody(), SSOUserInfo.class);
 
        if (userInfo == null || StringUtils.isEmpty(userInfo.getName())) {
            throw new RuntimeException("获取用户信息失败或用户名为空");
        }
 
        return userInfo;
    }
 
    /**
     * 创建本地会话
     */
    private String createLocalSession(SSOUserInfo userInfo) {
        // 根据SSO用户信息查找本地用户(根据工号匹配)
        SysUser localUser = findLocalUserByName(userInfo.getName());
 
        if (localUser == null) {
            throw new RuntimeException("用户不存在或未开通系统权限:" + userInfo.getName());
        }
 
        // 创建登录用户对象
        LoginUser loginUser = new LoginUser(localUser.getUserId(), localUser.getDeptId(), localUser, null);
 
        // 生成token
        return tokenService.createToken(loginUser);
    }
 
    /**
     * 根据工号查找本地用户
     */
    private SysUser findLocalUserByName(String workNumber) {
        if (StringUtils.isEmpty(workNumber)) {
            log.error("工号为空,无法查找用户");
            return null;
        }
 
        try {
            SysUser user = userService.selectUserByUserName(workNumber);
            if (user != null) {
                log.info("找到用户: {} - {}", workNumber, user.getNickName());
            } else {
                log.warn("未找到用户: {}", workNumber);
            }
            return user;
        } catch (Exception e) {
            log.error("查询用户失败: {}", workNumber, e);
            return null;
        }
    }
 
    /**
     * 根据客户端IP判断是否为内网
     */
    private boolean isInternalNetwork(String clientIp) {
        if (clientIp == null || clientIp.isEmpty()) {
            return false;
        }
 
        // 判断是否为内网网段 10.10.13.*
        return clientIp.startsWith("10.10.13.");
    }
 
    /**
     * 获取客户端真实IP
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
 
        // 如果有多个IP,取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
 
        log.info("客户端IP: {}", ip);
        return ip;
    }
 
    /**
     * 根据网络环境获取授权URL
     */
    private String getAuthorizeUrl(boolean isInternal) {
        return isInternal ? internalAuthorizeUrl : externalAuthorizeUrl;
    }
 
    /**
     * 根据网络环境获取Token URL
     */
    private String getTokenUrl(boolean isInternal) {
        return isInternal ? internalTokenUrl : externalTokenUrl;
    }
 
    /**
     * 根据网络环境获取用户信息URL
     */
    private String getUserinfoUrl(boolean isInternal) {
        return isInternal ? internalUserinfoUrl : externalUserinfoUrl;
    }
 
    /**
     * 根据网络环境获取回调URI
     */
    private String getRedirectUri(boolean isInternal) {
        return isInternal ? internalRedirectUri : externalRedirectUri;
    }
 
 
}