I\'m trying to get the user from spring context in an application spring as follows:
Authentication auth = SecurityContextHolder.getContext().getAuthenticati
This is my implementation, I've used TaskDecorator to copy the SecurityContext in the new thread, the new thread runs with this new SecurityContext even the user logout during the execution of the async task.
Xml declaration for executor
this is the class SecurityContextCopyingDecorator
package com.myapp.task;
import org.springframework.core.task.TaskDecorator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
public class SecurityContextCopyingDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
final Authentication a = SecurityContextHolder.getContext().getAuthentication();
return () -> {
try {
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(a);
SecurityContextHolder.setContext(ctx);
runnable.run();
} finally {
SecurityContextHolder.clearContext();
}
};
}
}
finally annotate some method to use threadPoolTaskExecutor in async mode
@Async
public void myAsyncMethod() {
}