Get user that runs an asynchronous method

前端 未结 3 2087
遥遥无期
遥遥无期 2021-01-17 18:11

I\'m trying to get the user from spring context in an application spring as follows:

Authentication auth = SecurityContextHolder.getContext().getAuthenticati         


        
3条回答
  •  长情又很酷
    2021-01-17 18:40

    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() {
    
    }
    

提交回复
热议问题