Search code examples
javaspringasynchronouslistenersecurity-context

SecurityUser in Async Spring Listeners


I am facing a problem and hope that someone can give me some advice. I have a restful Spring application which allows HTTP-requests. I am using spring security and offer oauth2. In my basic service, called by a controller, I am fetching the currently logged user via:

SecurityUser loggedUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

So far, that's all working fine. Furthermore, I am using events and event listeners implementing the org.springframework.context.ApplicationListener interface. I configured the application event multicaster the way that events are handled asynchronously (using a SimpleAsyncTaskExecutor).

The (obvious) problem arises when I try to use my service (and methods which rely on the currently logged user) in my listeners. They cannot access the context as they are working asynchronous. Hence, I cannot fetch the current user.

Can you give any advice how to solve the problem? Are there more options than to

  • save and extend the context somehow so that the async listeners can still access it? if so, how to do it?
  • change all the services methods to hand over the user via a parameter (instead of the service fetching the current user itself) and store its id e.g. in the event.

Thank you very much. Myself


Solution

  • You can use a DelegatingSecurityContextAsyncTaskExecutor instead of a SimpleAsyncTaskExecutor. The problem is that you only can get the user's context when the user is logged.