如果是401未经授权,请从RequestTemplate中删除标头,然后重试

时间:2019-06-22 12:11:11

标签: spring-boot spring-cloud-feign

我正在假请求中插入授权标头,但是在服务器发出401请求后,我使用相同的请求和标头重试,导致相同的错误。如果我手动使令牌过期,那么最终会出现2个旧的和新的授权标头,从而导致400错误。到目前为止,我看不到任何删除旧标头的方法,据我所知,是这样的:

@Bean
public RequestInterceptor oauth2ApplicationRequestInterceptor() {
    return new OAuth2FeignRequestInterceptor(getOAuth2ClientContext(), oauth2ApplicationResourceDetails()) {
        @Override
        public void apply(RequestTemplate template) {
            if (template.headers().containsKey("Authorization")) {
                // if Authorization exists then remove it
            } else {
                super.apply(template);
            }
        }
    };

如果服务器给我一个401错误,那么对我来说,手动过期令牌是唯一的方法。

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。 这是我解决问题的方法

@Override
public void apply(RequestTemplate template) {
    // We make a copy of the original headers
    Map<String, Collection<String>> originalHeaders = template.headers();
    // We copy the original headers in a new map
    Map<String, Collection<String>> newHeaders = new HashMap<String, Collection<String>>();
    for (Map.Entry<String, Collection<String>> originalEntry : originalHeaders.entrySet()) {
        // Except "Authorization" header
        if (!"Authorization".equals(originalEntry.getKey())) {
            newHeaders.put(originalEntry.getKey(), originalEntry.getValue());
        }
    }
    // This call will clear the template headers Map (see Feign sources)
    template.headers(null);
    // We add the new "Authorization" header to the new headers
    newHeaders.put("Authorization",
            Collections.singletonList(String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, getToken())));
    // Add the headers to the template
    template.headers(newHeaders);
}