hi i have some problems when use spring security in thread scope
System.out.println(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
new Thread(() -> System.out.println(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId())).start();
this two lines should give me current user id
the first line work as expected
the second line give me NullPointerException as there is no current user it is null value
i found this problem as i want to save many rows to the song table and it hava @CreatedBy user and this will ask for current user in thread and will fail as this will give null value for current user
If you want spawned threads to inherit SecurityContext
of the parent thread, you should set MODE_INHERITABLETHREADLOCAL
strategy.
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL)
There was an issue, when using this with thread pools. This seems to be fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With