async 처리를 할때 로그인된 정보를 가져 올 수 없는 문제를 부딪쳤다.
@async 처리가 아닌 경우에는 aspectj 에서 로그인 정보를 정상적으로 가져오지만 async 처리 시에는 해당 정보를 호출시 NPE 에러가 떨어졌다.
해당 문제를 해결하기 위해 구글링을 하던중에 아래와 같은 해결 방법을 보게 되었다.
아래는 stackoverflow
https://stackoverflow.com/questions/5246428/spring-security-and-async-authenticated-users-mixed-up
Spring Security and @Async (Authenticated Users mixed up)
I asynchronously invoke a method with Spring, using @Async. This method invokes another method annotated with @PreAuthorize, the Spring Security Annotation. To make the authorization work I have to...
stackoverflow.com
2가지 방법을 확인하였는데 나는 아래의 방법을 참조하여 해결하였다.
첫 번째 해결방법
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();
}
}
});
}
위와 같이 excute 실행 전 authentication을 변수에 담아 두었다가 실행시 재 설정해주는 방법이다 .
실제 적용 코드
두번째 방법
config 설정 시 아래와 같이 설정하는 방법이 있다.
@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);
}
다음에 같은 문제가 발생한다면 config 로 공통적으로 해결이 가능하게 수정하면 좋을것 같다는 생각이 작성중에 들어 전체 리소스 리팩토링을 진행해야 할듯 하다.
'코드 > dev' 카테고리의 다른 글
java dateTime 타임존 (2) | 2023.11.22 |
---|---|
Junit test filtering (2) | 2023.11.17 |
저장소에 올라간 브랜치 되돌리기 (2) | 2023.11.15 |
spring AOP & AspectJ (1) | 2023.11.15 |
mariaDB Schedule (3) | 2023.11.14 |