9

我正在运行一个 spring boot 应用程序,并且刚刚开始从 spring-cloud-netflix 集成 Hystrix。我正在使用 @HystrixCommand 来包装使用 feign 客户端进行的服务到服务调用。

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

这个 feign 客户端使用 spring 安全上下文向它发出的请求添加安全标头。

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

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

SecurityContextHolder.getContext().getAuthentication();

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

4

4 回答 4

12

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

hystrix.shareSecurityContext: true

于 2017-03-24T07:46:03.403 回答
4

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

@HystrixCommand(fallbackMethod = "updateThingFallback", commandProperties = {
        @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE")
})
于 2015-05-04T15:42:34.517 回答
2

我通过以下方式解决了这个问题:解决方案示例 但是这个示例是针对 spring-boot 应用程序的,我在 Tomcat 7 中应用了这个,两个主要变化是:

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

     @Override
            public void init(FilterConfig filterConfig) throws ServletException {
                HystrixPlugins.getInstance().registerCommandExecutionHook(new SecurityContextRegistratorCommandHook());
    }
    
于 2016-11-22T19:53:21.840 回答
1

或者,您可以使用 DelegatingSecurityContextExecutor 包装 Hystrix 使用的 Executor。

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

于 2016-05-27T21:49:50.347 回答