You could create a Runnable that sets the Authentication or SecurityContext to use one that is injected and then delegate to the Runnable you actually want. Something like...
Code:
public class SpringSecurityRunnableWrapper implements Runnable {
private SecurityContext context;
private Runnable delegate;
public SpringSecurityRunnableWrapper(SecurityContext context, Runnable delegate) {
this.context = context;
this.delegate = delegate;
}
public void run() {
try {
SecurityContextHolder.setContext(context);
delegate.run();
} finally {
SecurityContextHolder.clear();
}
}
Then to call it you would do something like:
Code:
Runnable worker = new MyCustomRunnableThatNeedsSecurity();
SecurityContext context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken("username","password",AuthorityUtils.createAuthorityList("ROLE_USER"));
Runnable securedWorker = new SpringSecurityRunnableWrapper(context, worker);
taskExecutor.execute(securedWorker);
Of Course you don't really need SpringSecurityRunnableWrapper since you could manage the SecurityContext inside of MyCustomRunnableThatNeedsSecurity directly, but it makes this more reusable and separates concerns.