If you want to access the security context in the asynchronous calls, You could implement the context aware thread pool executor to store the security context when creating threads like below.
public class CustomExecutor extends ThreadPoolTaskExecutor {
@Override
public <T> Future<T> submit(Callable<T> task) {
return super.submit(new ScopeAwareCallable<T>(task, SecurityContextHolder.getContext()));
}
public class ScopeAwareCallable<T> implements Callable<T> {
private Callable<T> callableTask;
private SecurityContext securityContext;
public ScopeAwareCallable(Callable<T> task, SecurityContext secContex) {
this.callableTask = task;
this.securityContext = secContex;
}
@Override
public T call() throws Exception {
if(securityContext != null){
SecurityContextHolder.setContext(securityContext);
}
try {
return callableTask.call();
}
finally {
SecurityContextHolder.clearContext();
}
}
}
configure this as your task executor in the spring configuration. If you're using the Runnable instead of Callable, then override other methods in ThreadPoolTaskExecutor which supports the Runnable execution as well.