Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Spring make the SecurityContext available to the thread executing a Hystrix Command

I'm running a spring boot app and just starting to integrate Hystrix from spring-cloud-netflix. I'm using @HystrixCommand to wrap a service-to-service call made with a feign client.

@HystrixCommand(fallbackMethod = "updateThingFallback")
def updateRemoteThing(thingResourceClient: ThingResourceClient, thing: Thing) {
    thingResourceClient.updateThing(thing) // Call using feign client
}

This feign client uses the spring security context to add security headers to the request it makes.

The problem I'm having is that when the HystrixCommand is executed it is run in a separate thread from a Hystrix thread pool and when my code tries to access the spring security context it is not available on the new thread.

I'm accessing the spring security context like this:

SecurityContextHolder.getContext().getAuthentication();

My Question is, does spring provide a way of passing the spring security context (and the application context) to the Hystrix threads that are running the Hystrix commands?

like image 626
Michael Larsen Avatar asked Apr 10 '15 16:04

Michael Larsen


4 Answers

Since Spring Cloud Netflix 1.2.0 you can enable sharing of security context with Hystrix using config param:

hystrix.shareSecurityContext: true

like image 158
Ondrej Bozek Avatar answered Oct 17 '22 14:10

Ondrej Bozek


I resolved this with: solution example But this example is for a spring-boot app, I applie this in a Tomcat 7 the two main changes was:

  1. The filter was created in the web.xml.
  2. In the init of:"class HystrixRequestContextEnablerFilter" I added: `

     @Override
            public void init(FilterConfig filterConfig) throws ServletException {
                HystrixPlugins.getInstance().registerCommandExecutionHook(new SecurityContextRegistratorCommandHook());
    }
    
like image 23
Seba Echarte Avatar answered Oct 17 '22 15:10

Seba Echarte


You should be able to get the ApplicationContext in your bean by the normal means. I can see two ways to pass the authentication object: 1) as a parameter to your method, or 2) run hystrix with Semaphore isolation rather than on a separate thread.

@HystrixCommand(fallbackMethod = "updateThingFallback", commandProperties = {
        @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE")
})
like image 35
spencergibb Avatar answered Oct 17 '22 15:10

spencergibb


Alternatively you can wrap the Executor used by Hystrix with DelegatingSecurityContextExecutor.

See https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#delegatingsecuritycontextexecutor

like image 26
Rob Winch Avatar answered Oct 17 '22 13:10

Rob Winch