I asynchronously invoke a method with Spring, using @Async. This method invokes another method annotated with @PreAuthorize, the Spring Security Annotation. To make the authorization work I have to set SecurityContextHolder mode to MODE_INHERITABLETHREADLOCAL, so that the authentication info is passed to the asynchronous call. Everything works fine so far.
However when I logout and login as a different user, in the asynchronous method the SecurityContextHolder stores the authentication info of the old user that has been logged out. It causes of course unwanted AccessDenied exception. There is no such problem with synchronous calls.
I have defined <task:executor id="executors" pool-size="10"/>, so may it be a problem that once thread in executors pool has been initialized it will not override authentication information?
I guess
MODE_INHERITABLETHREADLOCALdoesn’t work correctly with thread pool.As a possible solution you can try to subclass
ThreadPoolTaskExecutorand override its methods to propagateSecurityContextmanually, and then declare that executor instead of<task:executor>, something like this: