沙钢智慧能源系统后端代码
dengzedong
2024-12-06 77a5ab85c55cdd84b311b1d67d35ba4663be8b93
提交 | 用户 | 时间
94c44e 1 package com.iailab.module.shasteel.util.token;
D 2
3 import lombok.extern.slf4j.Slf4j;
4 import org.springframework.core.ParameterizedTypeReference;
5 import org.springframework.http.HttpHeaders;
6 import org.springframework.http.HttpMethod;
7 import org.springframework.http.MediaType;
8 import org.springframework.http.ResponseEntity;
9 import org.springframework.util.Assert;
10 import org.springframework.util.Base64Utils;
11 import org.springframework.util.ObjectUtils;
12 import org.springframework.web.client.RestTemplate;
13
14 import java.nio.charset.StandardCharsets;
15 import java.util.Map;
16
17 /**
18  * @author PanZhibao
19  * @Description
20  * @createTime 2024年11月21日
21  */
22 @Slf4j
23 public class IailabClient {
24
25     /**
26      * 平台地址
27      */
28     public static String BASE_URL;
29
30     /**
31      * 租户编号
32      */
33     public static Long TENANT_ID;
34
35     /**
36      * 客户端信息
37      */
38     private static String CLIENT_ID;
39     private static String CLIENT_SECRET;
40     private static String USERNAME;
41     private static String PASSWORD;
42     private static final String GRAND_TYPE = "password";
43     private static final String SCOPE = "user.read user.write";
44
45
46     private static final RestTemplate restTemplate = new RestTemplate();
47
48     // 鉴权token
49     public static String accessToken;
50     // 刷新token
51     public static String refreshToken;
52     // 鉴权token过期时间
53     public static Long expireTime;
54
55     private static final IailabClient iailabClient = new IailabClient();
56
57     private IailabClient() {
58 //        BASE_URL = PlatApplicationContext.getProperty("iailab.baseUrl");
59 //        TENANT_ID = Long.parseLong(PlatApplicationContext.getProperty("iailab.tenantId"));
60 //        CLIENT_ID = PlatApplicationContext.getProperty("iailab.clientId");
61 //        CLIENT_SECRET = PlatApplicationContext.getProperty("iailab.clientSecret");
62 //        USERNAME = PlatApplicationContext.getProperty("iailab.username");
63 //        PASSWORD = PlatApplicationContext.getProperty("iailab.password");
64
65         BASE_URL = "http://127.0.0.1:48080/admin-api/system";
f0a800 66         TENANT_ID = 176L;
94c44e 67         CLIENT_ID = "shasteel";
D 68         CLIENT_SECRET = "shasteel111111111111111";
69         USERNAME = "shasteel";
70         PASSWORD = "123456";
71     }
72
73     public static IailabClient getInstance() {
74         return iailabClient;
75     }
76
77     /**
78      * 用户名密码方式获取平台token
79      */
80     private static synchronized void authenticate() {
81         log.info("获取平台token");
82         // 1.1 构建请求头
83         HttpHeaders headers = new HttpHeaders();
84         addClientHeader(headers);
85         // 1.2 构建authenticate请求URL
86         String authenticateUrl = BASE_URL + "/oauth2/token?"
87                 // 密码模式的参数
88                 + "grant_type=" + GRAND_TYPE
89                 + "&username=" + USERNAME
90                 + "&password=" + PASSWORD
91                 + "&scope=" + SCOPE;
92         // 2. 执行请求
93         ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
94                 authenticateUrl,
95                 HttpMethod.POST,
96                 new org.springframework.http.HttpEntity<>(headers),
97                 new ParameterizedTypeReference<Map<String, Object>>() {
98                 });
99         Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");
100         log.info(exchange.toString());
101         Map<String, Object> authMap = exchange.getBody();
102         accessToken = authMap.get("access_token").toString();
103         refreshToken = authMap.get("refresh_token").toString();
104         expireTime = Long.valueOf(authMap.get("expires_time").toString());
105     }
106
107     private static synchronized void refreshToken() {
108         log.info("刷新token");
109         // 1.1 构建请求头
110         HttpHeaders headers = new HttpHeaders();
111         addClientHeader(headers);
112         // 1.2 构建authenticate请求URL
113         String authenticateUrl = BASE_URL + "/system/auth/client-refresh-token?refreshToken=" + refreshToken
114                 + "&clientId=" + CLIENT_ID;
115         // 2. 执行请求
116         ResponseEntity<Map<String, Object>> exchange = restTemplate.exchange(
117                 authenticateUrl,
118                 HttpMethod.POST,
119                 new org.springframework.http.HttpEntity<>(headers),
120                 new ParameterizedTypeReference<Map<String, Object>>() {
121                 });
122         Assert.isTrue(exchange.getStatusCode().is2xxSuccessful(), "响应必须是 200 成功");
123         Map<String, Object> authMap = exchange.getBody();
124         //刷新token过期,重新获取token
125         if (!ObjectUtils.isEmpty(authMap.get("code"))) {
126             Integer code = Integer.valueOf(authMap.get("code").toString());
127             if (code == 401) {
128                 authenticate();
129             }
130         } else {
131             accessToken = authMap.get("access_token").toString();
132             expireTime = Long.valueOf(authMap.get("expires_time").toString());
133         }
134     }
135
136     private static void addClientHeader(HttpHeaders headers) {
137         // client 拼接,需要 BASE64 编码
138         String client = CLIENT_ID + ":" + CLIENT_SECRET;
139         client = Base64Utils.encodeToString(client.getBytes(StandardCharsets.UTF_8));
140         headers.add("Authorization", "Basic " + client);
141         headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
142         headers.set("tenant-id", TENANT_ID.toString());
143     }
144
145     public static String getToken() {
146         //第一次请求或者token过期,需要重新获取token
147         if(ObjectUtils.isEmpty(IailabClient.accessToken)) {
148             IailabClient.authenticate();
149         } else if (IailabClient.expireTime < System.currentTimeMillis() / 1000) {
150             IailabClient.refreshToken();
151         }
152         
153         return accessToken;
154     }
155     public static Long getTenantId() {
156         return TENANT_ID;
157     }
158 }