Home > front end >  Parallel Stream and SpringSecurity
Parallel Stream and SpringSecurity

Time:06-30

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. 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? I believe this can cause security issues if there are multiple users accessing the service.

CodePudding user response:

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..

});
  • Related