Search code examples
spring-bootspring-cloudnetflix-feign

Forward a request header or the security context with a Feign client RequestInterceptor


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


Solution

  • 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 :

    1. Wrap the Callable in wrapCallable with, for example, an CallableWithAuthentication class that would hold the current authentication when constructed
    2. The CallableWithAuthentication 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).