Spring 에서 @Async를 통한 비동기 로직을 사용시
별도의 Thread이기 때문에 부모 Thread에서 사용하던
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Authentication을 생성된 별도 Thread에서는 참조할수 없다.
이에 대한 해결 방법은 2개가 제시된다.
MODE_INHERITABLETHREADLOCAL
SecurityContextHolder의 전략을 MODE_INHERITABLETHREADLOCAL 로 지정하여, ThreadLocal에 저장되는 SecurityContext를 하위 Thread의 ThreadLocal에도 전파 시키는 방법.
- 최근 Spring Security 에 생성된 issue 의 내용으로는
MODE_INHERITABLETHREADLOCAL 과 ThreadPool로 비동기 Thread 생성시 Thread가 재사용되며 잘못된 SecurityContext 가 사용될수 있다는 문제점을 제기 했다.
-> Pool로 관리되는 Thread 의 ThreadLocal 사용은 release 시에 해제 하지 않는다면, 잘못 사용될수 밖에 없다.
DelegatingSecurityContextRunnable, DelegatingSecurityContextExecutor
DelegatingSecurityContextRunnable 또는 DelegatingSecurityContextExecutor 을 사용하여 실행되는 Runnable Thread에 SecurityContext를 전파시키는 방법이 있다.
DelegatingSecurityContextExecutor를 @Async 사용시 참조하는 TaskExcutor를 랩핑하여 사용하면 된다.