沙钢智慧能源系统后端代码
dengzedong
2024-12-06 259beab5e89790d7cf58e5b19281e94ebc6f2c8a
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
package com.iailab.module.shasteel.config;
 
import com.iailab.module.shasteel.util.token.IailabClient;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
@Configuration
public class FeignTokenInterceptor implements RequestInterceptor {
 
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 从当前请求上下文中获取Token
        String token = getTokenFromCurrentRequest();
 
        if (token == null) {
            // 如果没有获取到Token,从system-server中获取token
            token = IailabClient.getToken();
            if (token!= null) {
                requestTemplate.header(HttpHeaders.AUTHORIZATION, token);
            }
        }
 
        Long tenantId = IailabClient.getTenantId();
        if (tenantId != null) {
            requestTemplate.header("tenant-id", String.valueOf(tenantId));
        }
    }
 
    private String getTokenFromCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes!= null) {
            return attributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
        }
        return null;
    }
}