Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching logged in user in service layer with spring security

I have an asynchronous method in the service layer which reads the message from the queue. I need to send the received message to the subscribers of the currently logged in user.

In my controller I fetch the user as

(CustomUserDetail)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

which works fine but the same code in the service layer throws a NullPointerException. May be due to SecurityContextHolder not being called within the same request response flow rather asynchronously but at the same time I think Spring Security keeps all the user security data in the session. So it should work fine.

Can anyone suggest a workaround. How do I fetch the logged in user in the service layer?

One possible way I feel can be adding the active user to the session when the controller method pushes the message to the queue & then retrieve the user from the session in the service layer.

like image 662
underdog Avatar asked Feb 08 '23 12:02

underdog


1 Answers

Spring SecurityContextHolder default mode is MODE_THREADLOCAL which means SecurityContextHolder is only available in same thread of execution.

Changing that to MODE_INHERITABLETHREADLOCAL, should give you access SecurityContextHolder in all the spawned thread.

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL)

should solve your problem.

like image 161
nestrocuation Avatar answered Feb 13 '23 22:02

nestrocuation