Spring Security and @Async (Authenticated Users mixed up)

后端 未结 6 566
离开以前
离开以前 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:27

    I guess MODE_INHERITABLETHREADLOCAL doesn't work correctly with thread pool.

    As a possible solution you can try to subclass ThreadPoolTaskExecutor and override its methods to propagate SecurityContext manually, and then declare that executor instead of , something like this:

    public void execute(final Runnable r) {
        final Authentication a = SecurityContextHolder.getContext().getAuthentication();
    
        super.execute(new Runnable() {
            public void run() {
                try {
                    SecurityContext ctx = SecurityContextHolder.createEmptyContext();
                    ctx.setAuthentication(a);
                    SecurityContextHolder.setContext(ctx);
                    r.run();
                } finally {
                    SecurityContextHolder.clearContext();
                }
            }
        });
    }
    

提交回复
热议问题