沙钢智慧能源系统后端代码
dengzedong
2024-12-06 7664fa0dbc023d192aeb94c7f2612e0fbe0e3cd7
提交 | 用户 | 时间
94c44e 1 package com.iailab.module.shasteel.config;
D 2
3 import com.iailab.module.shasteel.util.token.IailabClient;
4 import feign.RequestInterceptor;
5 import feign.RequestTemplate;
7664fa 6 import org.springframework.beans.factory.annotation.Autowired;
94c44e 7 import org.springframework.context.annotation.Configuration;
D 8 import org.springframework.http.HttpHeaders;
9 import org.springframework.web.context.request.RequestContextHolder;
10 import org.springframework.web.context.request.ServletRequestAttributes;
11
12 @Configuration
13 public class FeignTokenInterceptor implements RequestInterceptor {
14
7664fa 15     @Autowired
D 16     private IailabClient iailabClient;
17
94c44e 18     @Override
D 19     public void apply(RequestTemplate requestTemplate) {
20         // 从当前请求上下文中获取Token
21         String token = getTokenFromCurrentRequest();
22
23         if (token == null) {
24             // 如果没有获取到Token,从system-server中获取token
7664fa 25             token = iailabClient.getToken();
259bea 26             if (token!= null) {
D 27                 requestTemplate.header(HttpHeaders.AUTHORIZATION, token);
28             }
7664fa 29             Long tenantId = iailabClient.getTenantId();
9788d4 30             if (tenantId != null) {
D 31                 requestTemplate.header("tenant-id", String.valueOf(tenantId));
32             }
94c44e 33         }
D 34     }
35
36     private String getTokenFromCurrentRequest() {
37         ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
38         if (attributes!= null) {
39             return attributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
40         }
41         return null;
42     }
43 }