Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define global static header on Spring Boot Feign Client

I have a spring boot app and want to create a Feign client which has a statically defined header value (for auth, but not basic auth). I found the @Headers annotation but it doesn't seem to work in the realm of Spring Boot. My suspicion is this has something to do with it using the SpringMvcContract.

Here's the code I want to work:

@FeignClient(name = "foo", url = "http://localhost:4444/feign")
@Headers({"myHeader:value"})
public interface LocalhostClient {

But it does not add the headers.

I made a clean spring boot app with my attempts and posted to github here: github example

The only way I was able to make it work was to define the RequestInterceptor as a global bean, but I don't want to do that because it would impact other clients.

like image 612
Stimp Avatar asked Dec 04 '22 20:12

Stimp


2 Answers

You can also achieve this by adding header to individual methods as follows:

@RequestMapping(method = RequestMethod.GET, path = "/resource", headers = {"myHeader=value"})

Using @Headers with dynamic values in Feign client + Spring Cloud (Brixton RC2) discusses a solution for dynamic values using @RequestHeader.

like image 21
Ali Daniyal Avatar answered Feb 07 '23 04:02

Ali Daniyal


You can set a specific configuration class on your feign interface and define a RequestInterceptor bean in there. For example:

@FeignClient(name = "foo", url = "http://localhost:4444/feign", 
configuration = FeignConfiguration.class)
public interface LocalhostClient {
}

@Configuration
public class FeignConfiguration {

  @Bean
  public RequestInterceptor requestTokenBearerInterceptor() {
    return new RequestInterceptor() {
      @Override
      public void apply(RequestTemplate requestTemplate) {
        // Do what you want to do
      }
    };
  }
}
like image 57
onnoweb Avatar answered Feb 07 '23 04:02

onnoweb