I would like to forward a request header with a feign client RequestInterceptor but, within RequestInterceptor.apply
, RequestContextHolder.getRequestAttributes()
is null
, so is SecurityContextHolder.getContext().getAuthentication()
(where I could also eventually get the value of my header).
This used to work before upgrading to Spring-Cloud Brixton, where the hystrix commands must now probably be run in a separate thread, because changing to the following parameter solves the problem :
hystrix.command.default.execution.isolation.strategy: SEMAPHORE
Now, I'm not too keen on changing this kind of default values if not necessary, is there another, recommended, way of forwarding headers now ?
Thanks
Using the Header Annotation In this situation, we might configure that request header as part of the client. A typical example is to include a Content-Type header. Using the @Header annotation, we can easily configure a static request header. We can define this header value either statically or dynamically.
Let's implement the Feign in our project and invoke other microservices using Feign. Step 1: Select currency-conversion-service project. Step 2: Open the pom. xml and add the Feign dependency.
Spring Interceptor are used to intercept client requests and process them. Sometimes we want to intercept the HTTP Request and do some processing before handing it over to the controller handler methods. One example of this processing can be logging for the request before its passed onto the specific handler method.
For Spring Boot 2+ / Spring Cloud Finchley +, if you just need the security context you can set the following property :
hystrix.shareSecurityContext=true
And the request interceptor should work.
For other uses cases or earlier versions (many thanks to Spring Cloud Sleuth for the inspiration) :
"All" you have to do is implement an HystrixConcurrencyStrategy
that passes the information along each time there is a thread change. The class that does something very similar in Sleuth is here.
For my specific case I would :
Callable
in wrapCallable
with, for example, an CallableWithAuthentication
class that would hold the current authentication when constructedCallableWithAuthentication
call
method would first restore the previously saved Authentication
, then call the original action, then clean up the current Authentication
, et voilà.Once your HystrixConcurrencyStrategy
is up your request interceptor will work again, even with Thread isolation.
Note check the rest of the project there are lots of other interesting instrumenting stuff (for RxJava for example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With