liusuyi
2025-11-18 5c2f353bfdaea493f043ea021c742f1b93bae46c
ard-work/src/main/java/com/ard/work/component/forest/TokenInterceptor.java
@@ -1,18 +1,18 @@
package com.ard.work.component.forest;
import com.ard.work.config.TyConfiguration;
import com.ard.work.domain.receiver.AccessTokenReceiver;
import com.ard.work.service.IArdServerInfoService;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.interceptor.ForestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
@Slf4j
public class TokenInterceptor<T> implements Interceptor<T> {
public class TokenInterceptor implements ForestInterceptor {
    @Resource
    private TyConfiguration tyConfiguration;
    private IArdServerInfoService ardServerService;
    /**
     * 该方法在请求发送之前被调用, 若返回false则不会继续发送请求
@@ -21,14 +21,19 @@
     */
    @Override
    public boolean beforeExecute(ForestRequest req) {
        log.info("invoke Simple beforeExecute");
        // 执行在发送请求之前处理的代码
        // 从缓存里获取token
        AccessTokenReceiver accessToken = tyConfiguration.getAccessToken();
        req.addHeader("x-cid", accessToken.getCompanyId());
        req.addHeader("x-token", accessToken.getAccessToken());
        // req.addHeader("Authorization", ""));  // 添加Header
        // req.addQuery("username", "foo");  // 添加URL的Query参数
        return true;  // 继续执行请求返回true
        try {
            String serverId = (String) req.getVariableValue("serverId");
            AccessTokenReceiver accessToken = ardServerService.getAccessToken(serverId);
            if (accessToken == null) {
                log.warn("AccessToken 为 null, serverId={}", serverId);
                return false; // 阻止请求继续
            }
            req.addHeader("x-cid", accessToken.getCompanyId());
            req.addHeader("x-token", accessToken.getAccessToken());
        } catch (Exception e) {
            log.error("TokenInterceptor 处理异常:{}", e.getMessage());
            return false;
        }
        return true;
    }
}