0 day streak
java / intermediate
Snippet

Propagating Security Context Across Asynchronous Threads with DelegatingSecurityContextAsyncTaskExecutor

By default, Spring Security stores authentication tokens in a `ThreadLocal` strategy (`MODE_THREADLOCAL`). As a consequence, spawned background threads invoked via `@Async` lose access to the current `SecurityContext`. Wrapping the task executor in a `DelegatingSecurityContextAsyncTaskExecutor` ensures security context snapshots are transparently transferred to the worker threads before task execution and cleared afterward.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableAsync
public class AsyncSecurityConfig {
@Bean(name = "securityAwareExecutor")
public AsyncTaskExecutor securityAwareExecutor() {
ThreadPoolTaskExecutor delegate = new ThreadPoolTaskExecutor();
delegate.setCorePoolSize(4);
delegate.setMaxPoolSize(16);
delegate.setQueueCapacity(100);
delegate.setThreadNamePrefix("secure-async-");
delegate.initialize();
return new DelegatingSecurityContextAsyncTaskExecutor(delegate);
}
}
spring
Breakdown
1
@EnableAsync
Enables Spring's asynchronous method execution capabilities across the application context.
2
ThreadPoolTaskExecutor delegate = new ThreadPoolTaskExecutor();
Configures the underlying standard Java thread pool with pool sizing and queue capacity.
3
return new DelegatingSecurityContextAsyncTaskExecutor(delegate);
Decorates the executor so that submitted Runnables and Callables copy the caller's SecurityContext into the worker thread.