0

I am inserting an authorization header in a feign request but upon a 401 from the server I am retrying with the same request and same header, resulting in the same error. If I expire manually the token then I end up with 2 Authorization headers old and new resulting in a 400 error. So far I don't see any way of removing the old header and as far as I got was something like this:

@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);
            }
        }
    };

Expiring manually the token is the only way for me at the moment if server gives me a 401 error.

Oh hi Mark
  • 153
  • 1
  • 8
  • 28

1 Answers1

0

I got the same issue. Here is the way I've solved it

@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);
}
lcn
  • 1