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

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.