Spring Cloud Feign如何实现JWT令牌中继以传递认证信息
import feign.RequestInterceptor;
import feign.RequestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
@Component
public class FeignJwtInterceptor implements RequestInterceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
@Autowired
private HttpServletRequest request;
@Override
public void apply(RequestTemplate template) {
// 检查原始请求是否有认证头,并将其传递给Feign客户端
Enumeration<String> headers = request.getHeaders(AUTHORIZATION_HEADER);
while (headers.hasMoreElements()) {
String header = headers.nextElement();
template.header(AUTHORIZATION_HEADER, header);
}
}
}
这段代码定义了一个Feign的拦截器,用于从当前的HttpServletRequest中获取JWT令牌,并将其添加到Feign客户端发起的请求中。这样,Feign客户端在访问远程服务时就可以使用这个令牌进行身份验证。
评论已关闭