Spring Security and @Async (Authenticated Users mixed up)

后端 未结 6 555
离开以前
离开以前 2020-11-27 13:03

I asynchronously invoke method with Spring, using @Async.This method invokes other method annotated with @PreAuthorize, Spring Security Annotation. To make authorization wor

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 13:22

    I also ran into that problem. It is important to configure the ThreadPoolTaskExecutor correctly using the DelegatingSecurityContextAsyncTaskExecutor. Also it is important to call the initialize() method, otherwise an error is thrown.

    // define the TaskExecutor as a bean
    @Bean("threadPoolTaskExecutor")
    public TaskExecutor getAsyncExecutor() {
    
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      executor.setCorePoolSize(20);
      executor.setMaxPoolSize(1000);
      executor.setWaitForTasksToCompleteOnShutdown(true);
      executor.setThreadNamePrefix("Async-");
      executor.initialize(); // this is important, otherwise an error is thrown
      return new DelegatingSecurityContextAsyncTaskExecutor(executor); // use this special TaskExecuter
    }
    

    // the method in your business logic which is called async
    @Override
    @Async("threadPoolTaskExecutor")
    public void yourLogic() {
      [..]
    }
    

提交回复
热议问题