Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring security current user in thread

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

like image 299
ashraf revo Avatar asked Dec 05 '22 15:12

ashraf revo


1 Answers

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.

like image 56
Ramanujan R Avatar answered Dec 19 '22 23:12

Ramanujan R