Parallel Stream and SpringSecurity

1.3k views Asked by At

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.

1

There are 1 answers

3
minh tri Vo On BEST ANSWER

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

});