0

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.

Rye
  • 33
  • 5
  • Does this answer your question? [Null principal when get security context in parallelStream](https://stackoverflow.com/questions/48076410/null-principal-when-get-security-context-in-parallelstream) – Datz Oct 18 '22 at 22:33

1 Answers1

0

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

});
minh tri Vo
  • 524
  • 4
  • 11
  • See the answers here and why not to do this: https://stackoverflow.com/a/48076704/9224219 – Datz Oct 18 '22 at 22:32