Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null principal when get security context in parallelStream [duplicate]

When I try to obtain the principal from the security context in a parallel stream, it always returns null when isn't in the main thread.

The following piece of code fails when the user is authenticated:

listOfSomething.parallelStream()
                .foreach(el -> { 
if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() == null){
            throw new RuntimeException();
}});

The documentation says:

Interface defining the minimum security information associated with the current thread of execution.

But, is there any way to do it? It starts in main thread and use ForkJoinPool

Thank you!

like image 647
Ganchix Avatar asked Aug 10 '26 01:08

Ganchix


1 Answers

It seems that you need to use a different SecurityContextHolder strategy. See https://docs.spring.io/spring-security/site/docs/5.0.0.RELEASE/reference/htmlsingle/#securitycontextholder-securitycontext-and-authentication-objects for more details on how to change it

like image 95
artie Avatar answered Aug 12 '26 16:08

artie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!