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