【问题标题】:Null principal when get security context in parallelStream [duplicate]在 parallelStream 中获取安全上下文时为空主体 [重复]
【发布时间】:2018-01-03 11:24:43
【问题描述】:

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

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

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

文档说:

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

但是,有什么办法吗?它从主线程开始并使用 ForkJoinPool

谢谢!

【问题讨论】:

  • 这不是重复的。在链接的问题中,OP 显式生成了一个线程,并尝试从该线程访问SecurityContext。在这种情况下,我们正在处理一个子线程,MODE_INHERITABLETHREADLOCAL 成功地传播了SecurityContext。在这里,我们使用parallelStream(),它将使用来自 fork/join 池(依赖于实现)的线程,这些线程可能不是启动线程的子线程。
  • This answer 可能是一个更有帮助的指针。对于并行流操作期间SecurityContext 传播的情况,我自己还没有验证。

标签: java spring spring-boot spring-security stream


【解决方案1】:

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

【讨论】:

  • 酷!谢谢!我正在寻找的模式是SecurityContextHolder.MODE_INHERITABLETHREADLOCAL
  • 不要这样做! 不应在并行流中使用安全上下文。 ParallelStream 使用共同共享的ForkJoinPool.commonPool,而MODE_INHERITABLETHREADLOCAL 将导致此处描述的非常讨厌的安全问题:github.com/spring-projects/spring-security/issues/6856。如果您迫切需要使用并行流,则需要将其绑定到自定义的 ForkJoinPool,该 ForkJoinPool 不会在不同的应用程序用户之间共享。见stackoverflow.com/questions/21163108/…
猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2015-10-06
  • 2015-11-29
  • 2012-01-25
相关资源
最近更新 更多