Does Spring provide SecurityContext access for the thread executing the Hystrix command

I am launching the spring boot application and just starting to integrate Hystrix from spring -cloud-netflix. I am using @HystrixCommand to transfer a service call to a service created using a fake 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 ran into is that when running HystrixCommand it starts in a separate thread from the Hystrix thread pool and when my code tries to access the spring security context, it is not available in the new thread.

I refer to the spring security context as follows:

 SecurityContextHolder.getContext().getAuthentication(); 

My question is: does spring provide a way to pass spring security context (and application context) to Hystrix threads that run Hystrix commands?

+5
source share
4 answers

You can get ApplicationContext in your bean in the usual ways. I can see two ways to pass the authentication object: 1) as a parameter for your method, or 2) run hystrix with semaphore isolation , and not on a separate thread.

 @HystrixCommand(fallbackMethod = "updateThingFallback", commandProperties = { @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE") }) 
+3
source

Since Spring Cloud Netflix 1.2.0 you can enable security context sharing with Hystrix using the configuration parameter

hystrix.shareSecurityContext: true

+3
source

I solved this with a solution example But this example is for a spring-boot application, I use it in Tomcat 7, the following two main changes:

  • The filter was created in web.xml.
  • In init: "class HystrixRequestContextEnablerFilter" I added: `

      @Override public void init(FilterConfig filterConfig) throws ServletException { HystrixPlugins.getInstance().registerCommandExecutionHook(new SecurityContextRegistratorCommandHook()); } 
+2
source

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

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

+1
source

All Articles