使用 feign.RequestInterceptor 进行认证操作

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,其它的系统间认证完全可以使用相同的思路搞定。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值