Search code examples
javaspring-bootmultithreadingspring-securityjava-stream

Spring SecurityContext not available when using parallelStream


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 one thread to another. I get a NullPointerException when getting the authentication principal. Is there a correct way of doing this?

I want a solution that does NOT involve setting the SecurityContextHolder's strategy to MODE_INHERITABLETHREADLOCAL. I believe this can cause security issues if there are multiple users accessing the service.


Solution

  • 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..
    
    });