【问题标题】:graphql-java nested resolvers are executed in different thread have different Spring security contextsgraphql-java 嵌套解析器在不同线程中执行具有不同的 Spring 安全上下文
【发布时间】:2019-08-30 11:29:24
【问题描述】:

我正在使用 graphql-java,它在不同的线程中执行不同的嵌套解析器。

我有一个关于 Spring Security 的自定义过滤器,它从 Authorization Header 中解析 Bearer 令牌并将其添加到当前的 Spring Security 上下文中。

我暂时能够通过侦听 ContextRefreshedEvent 并将策略强制为 Global 来解决问题,如您在此处看到的:

    @EventListener
    fun setupSecurityContext(event: ContextRefreshedEvent) {
        SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL)
    }

我对这个解决方案不满意,因为当我想接收作为解析器上的参数传递的令牌时,我必须通过全局静态调用访问解析器上的令牌。

SecurityContextHolder.getContext().authentication.principal

我认为这不是一个好习惯。我猜一个请求的数据可能会被不同的线程暴露给另一个用户。

【问题讨论】:

    标签: java spring kotlin spring-security graphql-java


    【解决方案1】:

    我在使用改造客户端时遇到了同样的问题。 我所需要的只是将 spring 委托执行器设置为 okhttp 调度程序,如下所示:

    @Bean
    DelegatingSecurityContextExecutorService dispatcherExecutor() {
        return new DelegatingSecurityContextExecutorService(
                new ThreadPoolExecutor(
                        0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                        new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false)
                )
        );
    }
    
    @Bean
    OkHttpClient okHttpClient() {
        var interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
    
        return new OkHttpClient.Builder()
                .connectTimeout(retrofitConnectionTimeout, TimeUnit.SECONDS)
                .readTimeout(retrofitConnectionTimeout, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .dispatcher(new Dispatcher(dispatcherExecutor()))
                .build();
    }
    

    graphql呢,请看graphql.execution.ExecutorServiceExecutionStrategy。它允许设置graphql异步调用执行器服务,所以你可以在这里传递spring委托执行器服务。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 2019-10-14
      • 2012-11-19
      • 2019-11-06
      • 1970-01-01
      • 2018-08-25
      相关资源
      最近更新 更多