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