feign攜帶token

人在代码在發表於2024-04-18

方式1:

@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
requestTemplate.header("token", request.getHeader("token"));
}
}

}
方式2:

public class BladeFeignRequestHeaderInterceptor implements RequestInterceptor {

@Override
public void apply(RequestTemplate requestTemplate) {
HttpHeaders headers = BladeHttpHeadersContextHolder.get();
ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
if (servletRequestAttributes != null) {
HttpServletRequest request = servletRequestAttributes.getRequest();
String TenantId = request.getHeader(TokenConstant.TENANT_ID);
String authorization = request.getHeader(SecureConstant.BASIC_HEADER_KEY);
String EcchAuth = request.getHeader(TokenConstant.HEADER);
// 設定請求頭資訊
requestTemplate.header(TokenConstant.TENANT_ID, TenantId);
requestTemplate.header(SecureConstant.BASIC_HEADER_KEY, authorization);
requestTemplate.header(TokenConstant.HEADER, EcchAuth);
requestTemplate.header(TraceConstant.HEADER_TRACE_ID, TraceIdUtil.get());
if (headers != null && !headers.isEmpty()) {
headers.forEach((key, values) -> {
values.forEach(value -> requestTemplate.header(key, value));
});
}
}
}

}

相關文章