1. feign.RequestInterceptor介绍
1.1 用途
老外是这么说的:
When you need to change all requests, regardless of their target,
you’ll want to configure a RequestInterceptor. For example, if you are
acting as an intermediary, you might want to propagate the
X-Forwarded-For header。
意思就是当使用Feign客户端进行服务之间的交互时,可以使用RequestInterceptor来修改请求的相关信息,比如Header。
1.2 代码
public interface RequestInterceptor {
void apply(RequestTemplate var1);
}
当把这个RequestInterceptor 注入到容器后,所有Feign请求都会经过这个方法,因此我们可以在这个apply中去修改请求的相关参数,从而完成诸如认证,鉴权之类参数的设置。
2.2 使用feign.RequestInterceptor完成Xxl登录认证
@Slf4j
@Component(XxlJobAuthInterceptor.NAME)
public class XxlJobAuthInterceptor implements RequestInterceptor {
public static final String NAME = "XxlJobAuthInterceptor";
@Autowired
private XxlJobUserApi xxlJobUserApi;
private final String LOGIN_IDENTITY_KEY = "XXL_JOB_LOGIN_IDENTITY";
@Value("${xxl.username}")
private String username;
@Value("${xxl.password}")
private String password;
@Override
public void apply(RequestTemplate requestTemplate) {
Response loginResponse = xxlJobUserApi.login(username, password, "off");
Map<String, Collection<String>> headers = loginResponse.headers();
Collection<String> acceptCookies = headers.get(HttpHeader.SET_COOKIE.lowerCaseName());
requestTemplate.header(HttpHeader.COOKIE.name(),acceptCookies);
}
}
我这里是用来登录Xxl-Job,其它的系统间认证完全可以使用相同的思路搞定。
Feign RequestInterceptor:实现跨系统登录认证示例
本文详细介绍了Feign库中的RequestInterceptor接口及其用途,展示了如何使用它在Xxl-Job场景下进行登录认证,并扩展到其他系统间的认证。通过实例代码,学习者将理解如何在Feign请求头中添加和修改参数,以实现统一的权限管理。
2万+

被折叠的 条评论
为什么被折叠?



