【Spring Cloud】feign调用携带token
在Feign中携带Token进行调用,可以通过定义一个Feign的拦截器来实现。以下是一个简单的示例:
- 首先,创建一个Feign的拦截器:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class FeignTokenInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("Authorization"); // 假设token在请求头的Authorization字段
template.header("Authorization", token); // 添加token到请求头
}
}
}
- 然后,在Feign客户端配置中添加这个拦截器:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "service-provider", url = "http://localhost:8080", configuration = FeignClientConfig.class)
public interface ServiceProviderClient {
@GetMapping("/api/resource")
String getResource();
}
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignClientConfig {
@Bean
public RequestInterceptor requestInterceptor() {
return new FeignTokenInterceptor();
}
}
在这个示例中,FeignTokenInterceptor
拦截器会从当前请求中取出Authorization
头部的值,并将其添加到Feign客户端发起的每个请求中。这样,Feign客户端在调用远程服务时就会携带上token了。
评论已关闭