简体   繁体   English

并行流和 SpringSecurity

[英]Parallel Stream and SpringSecurity

I have the following block of code:我有以下代码块:

myList.parallelStream().forEach(item -> {
  //this external api call will use the current
  //spring security to populate the headers with values
  //that is extracted from jwt token

  var response = externalApi.getFoo(item.getAttribute());

  ..do something..

});

The problem is, the SecurityContext does not get passed from 1 thread to another.问题是,SecurityContext 没有从一个线程传递到另一个线程。 I get null pointer when getting the Authentication principal.获取身份验证主体时得到空指针。 Is there a correct way of doing this?有这样做的正确方法吗?

One that does NOT involve setting the SecurityContextHolder's strategy to MODE_INHERITABLETHREADLOCAL?不涉及将 SecurityContextHolder 的策略设置为 MODE_INHERITABLETHREADLOCAL 的一种? I believe this can cause security issues if there are multiple users accessing the service.我相信如果有多个用户访问该服务,这可能会导致安全问题。

I would simply set the authentication information to each thread.我只需将身份验证信息设置为每个线程。 Do you find any problem with this approach?你觉得这种方法有什么问题吗?

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
myList.parallelStream().forEach(item -> {
  SecurityContextHolder.getContext().setAuthentication(authentication);
  var response = externalApi.getFoo(item.getAttribute());
  SecurityContextHolder.getContext().setAuthentication(null);

  ..do something..

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM