Spring 是否使 SecurityContext 可用于执行 Hystrix 命令的线程

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

我正在 运行 安装 spring 引导应用程序,并且刚刚开始从 spring-cloud-netflix 集成 Hystrix。我正在使用 @HystrixCommand 包装一个由假客户端发出的 service-to-service 调用。

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

这个伪装客户端使用 spring 安全上下文为其发出的请求添加安全性 headers。

我遇到的问题是,当执行 HystrixCommand 时,它 运行 在一个独立于 Hystrix 线程池的线程中,当我的代码试图访问 spring 安全上下文时,它在新线程上不可用。

我正在像这样访问 spring 安全上下文:

SecurityContextHolder.getContext().getAuthentication();

我的问题是,spring 是否提供了一种将 spring 安全上下文(和应用程序上下文)传递给 运行 执行 Hystrix 命令的 Hystrix 线程的方法?

您应该能够通过正常方式在您的 bean 中获取 ApplicationContext。我可以看到两种传递身份验证对象的方法:1) 作为方法的参数,或 2) 运行 hystrix with Semaphore isolation 而不是在单独的线程上。

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

或者,您可以使用 DelegatingSecurityContextExecutor 包装 Hystrix 使用的执行器。

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

我解决了这个问题:solution example 但是这个例子是针对 spring-boot 应用程序的,我在 Tomcat 7 中应用了这个,两个主要的变化是:

  1. 过滤器是在 web.xml 中创建的。
  2. 在:"class HystrixRequestContextEnablerFilter" 的初始化中我添加了:`

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

Spring Cloud Netflix 1.2.0 开始,您可以使用配置参数启用与 Hystrix 的安全上下文共享:

hystrix.shareSecurityContext: true