Class SecurityContextTaskDecorator

java.lang.Object
com.fayupable.logged.spring.security.SecurityContextTaskDecorator
All Implemented Interfaces:
org.springframework.core.task.TaskDecorator

public final class SecurityContextTaskDecorator extends Object implements org.springframework.core.task.TaskDecorator
TaskDecorator that carries the submitting thread's Spring Security SecurityContext into whatever thread Spring's @Async infrastructure actually runs the task on.

The Spring Security counterpart to com.fayupable.logged.spring.aspect.FlowContextTaskDecorator: that class carries this library's own call-chain tracking across an @Async boundary, this one carries the authenticated user across the same boundary. Combine both on the same executor if both are needed:


 @Bean
 public TaskExecutor taskExecutor() {
     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
     executor.setTaskDecorator(runnable ->
             new FlowContextTaskDecorator().decorate(
                     new SecurityContextTaskDecorator().decorate(runnable)));
     executor.initialize();
     return executor;
 }
 

Without this registration, this library's caller identity resolution silently falls back to an IP address or "unknown" for any nested @Logged call made from within an @Async method dispatched through the decorated executor, losing the authenticated user entirely.

  • Constructor Details

    • SecurityContextTaskDecorator

      public SecurityContextTaskDecorator()
  • Method Details

    • decorate

      public Runnable decorate(@NonNull Runnable runnable)
      Captures the calling thread's current SecurityContext and returns a wrapped task that restores it before running runnable and restores the executor thread's own previous security context again afterward, regardless of whether runnable completes normally or throws.
      Specified by:
      decorate in interface org.springframework.core.task.TaskDecorator
      Parameters:
      runnable - the task Spring's @Async infrastructure is about to hand off to an executor thread
      Returns:
      a task carrying the calling thread's security context