潘志宝
10 天以前 a365eb1d7213c5f28c6d2fc2b8f87099d71d17d4
提交 | 用户 | 时间
cb8c71 1 package com.iailab.sdk.auth.client;
H 2
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import com.iailab.sdk.auth.client.vo.AuthLoginReqVO;
b233cc 5 import com.iailab.sdk.auth.config.AuthProperties;
cb8c71 6 import org.springframework.core.ParameterizedTypeReference;
H 7 import org.springframework.http.*;
8 import org.springframework.stereotype.Component;
9 import org.springframework.stereotype.Service;
10 import org.springframework.util.Assert;
b233cc 11 import org.springframework.util.Base64Utils;
H 12 import org.springframework.util.ObjectUtils;
cb8c71 13 import org.springframework.web.client.RestTemplate;
H 14
b233cc 15 import java.nio.charset.StandardCharsets;
cb8c71 16 import java.util.*;
b233cc 17
H 18 import static com.iailab.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
19 import static com.iailab.framework.common.exception.util.ServiceExceptionUtil.exception;
20 import static com.iailab.sdk.auth.enums.ErrorCodeConstants.*;
cb8c71 21
H 22 /**
23  * @author Houzhongjian
24  * @Description
25  * @createTime 2025年02月18日
26  */
27 @Component
28 @Service
29 public class IailabAuthClient {
30
31     private static final RestTemplate restTemplate = new RestTemplate();
b233cc 32
H 33     private static AuthProperties authProperties;
34
35     public static void setAuthProperties(AuthProperties properties) {
36         authProperties = properties;
37     }
38
39     private static final String GRAND_TYPE = "password";
40
41     private static final String SCOPE = "user.read user.write";
42
43     // 鉴权token
44     public static String accessToken;
45     // 刷新token
46     public static String refreshToken;
47     // 鉴权token过期时间
48     public static Long expireTime;
cb8c71 49
H 50     /**
51      * 用户名密码方式获取平台token
52      */
b233cc 53     public static synchronized void authenticate() throws Exception {
cb8c71 54         System.out.println("登录获取平台token");
H 55         // 1.1 构建请求头
56         HttpHeaders headers = new HttpHeaders();
57         addClientHeader(headers);
58         headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
59         // 1.2 构建authenticate请求URL
60         // 1.2 构建authenticate请求URL
b233cc 61         String authenticateUrl = authProperties.getBaseUrl() + "/system/oauth2/token?"
H 62                 // 密码模式的参数
63                 + "&grant_type=" + GRAND_TYPE
64                 + "&username=" + authProperties.getUsername()
65                 + "&password=" + authProperties.getPassword()
66                 + "&scope=" + SCOPE;
cb8c71 67         // 2. 执行请求
H 68         ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
69                 authenticateUrl,
70                 HttpMethod.POST,
71                 new HttpEntity<>(headers),
72                 new ParameterizedTypeReference<Map<String, Object>>() {
73                 });
b233cc 74         Map<String, Object> authMap = exchange.getBody();
H 75         if(AUTH_BAD_CREDENTIALS.getCode().equals(authMap.get("code"))) {
76             throw exception(AUTH_BAD_CREDENTIALS);
77         } else if(AUTH_LOGIN_BAD_CREDENTIALS.getCode().equals(authMap.get("code"))) {
78             throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
79         }
80         Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");
81         accessToken = authMap.get("access_token").toString();
82         refreshToken = authMap.get("refresh_token").toString();
83         expireTime = Long.valueOf(authMap.get("expires_time").toString());
84     }
85
86     public static synchronized void refreshToken() throws Exception {
87         System.out.println("刷新token");
88         // 1.1 构建请求头
89         HttpHeaders headers = new HttpHeaders();
90         addClientHeader(headers);
91         // 1.2 构建authenticate请求URL
92         String authenticateUrl = authProperties.getBaseUrl() + "/system/auth/client-refresh-token?refreshToken=" + refreshToken+ "&clientId=" + authProperties.getClientId();
93         // 2. 执行请求
94         ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
95                 authenticateUrl,
96                 HttpMethod.POST,
97                 new HttpEntity<>(headers),
98                 new ParameterizedTypeReference<Map<String, Object>>() {
99                 });
100         Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");
101         Map<String, Object> authMap = exchange.getBody();
102         //刷新token过期,重新获取token
103         if (!ObjectUtils.isEmpty(authMap.get("code"))) {
104             Integer code = Integer.valueOf(authMap.get("code").toString());
105             if (code == 401) {
106                 authenticate();
107             } else {
108                 throw exception(AUTH_REFRESH_TOKEN_ERROR);
109             }
110         } else {
111             accessToken = authMap.get("access_token").toString();
112             expireTime = Long.valueOf(authMap.get("expires_time").toString());
113         }
cb8c71 114     }
H 115
116     private static void addClientHeader(HttpHeaders headers) {
b233cc 117         // client 拼接,需要 BASE64 编码
H 118         String client = authProperties.getClientId() + ":" + authProperties.getClientSecret();
119         client = Base64Utils.encodeToString(client.getBytes(StandardCharsets.UTF_8));
120         headers.add("Authorization", "Basic " + client);
cb8c71 121         headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
b233cc 122         headers.set("tenant-id", authProperties.getTenantId());
cb8c71 123     }
H 124
125 }