在并行流中获取安全上下文时主体为空

Gan*_*hix 6 java spring stream spring-security spring-boot

当我尝试从并行流中的安全上下文获取主体时,如果主体不在主线程中,它总是返回 null。

当用户通过身份验证时,以下代码段失败:

listOfSomething.parallelStream()
                .foreach(el -> { 
if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() == null){
            throw new RuntimeException();
}});
Run Code Online (Sandbox Code Playgroud)

文档说:

定义与当前执行线程关联的最小安全信息的接口。

但是,有什么办法可以做到吗?它在主线程中启动并使用 ForkJoinPool

谢谢你!

art*_*tie 4

看来您需要使用不同的SecurityContextHolder策略。有关如何更改它的更多详细信息,请参阅https://docs.spring.io/spring-security/site/docs/5.0.0.RELEASE/reference/htmlsingle/#securitycontextholder-securitycontext-and-authentication-objects

  • *不要这样做!* 安全上下文不应在并行流中使用。`ParallelStream` 使用公共共享的 `ForkJoinPool.commonPool`,并且 `MODE_INHERITABLETHREADLOCAL` 将导致此处描述的非常严重的安全问题:https://github.com/spring-projects/spring-security/issues/6856。如果您迫切需要使用并行流,那么您需要将其绑定到自定义 ForkJoinPool,该自定义 ForkJoinPool 不在不同应用程序用户之间共享。请参阅/sf/ask/1481417591/ (10认同)