상세 컨텐츠

본문 제목

SpringSecurity [WebAsyncManagerIntegrationFilter]

SpringSecurity

by 성찬우 2022. 7. 15. 02:49

본문

Async = 비동기

 

Web 비동기 관리자 통합 필터이다.  우리가 오늘 해볼 것은. 

 

다른 Thread 안에서 SecurityContextHolder안에 있는 Principal 정보는 동일한지 확인해 볼 것이다. 

 

Callable이라는 자바에서 지원해주는 기능을 사용할 것이다. 

 

우선 컨트롤러에서 

@GetMapping("/tests")
@ResponseBody
public Callable<String> testController(){
    
}

여기서 return new Callable 해주면 바로 overice 메소드가 나타난다.

@GetMapping("/tests")
@ResponseBody
public Callable<String> testController(){
[1]-----------여기에 들어가는 설정들-------------
    return new Callable<String>() {
        @Override
        public String call() throws Exception {
       [2] ------------------여기에 들어가는 설정들----------------
            return null;
        }
    };
}

이렇게 .

 

저렇게 1번과 2번을 나눈 이유는 1번과 2번은 각기 다른 쓰레드를 사용하기 떄문이다. 

만약 다른 쓰레드를 사용 할 시에 같은 Principal 객체를 가져올 수 있는지 확인해보고자 한다. 

 

 

첫번 째. 메소드를 하나 만들어준다.

public static void log(String message){
    System.out.println(message);
    Thread thread = Thread.currentThread();
    System.out.println("this is thread location:" +thread.getName());
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    System.out.println("this is principal:"+principal);
}

이 메소드는 위에 1-2번 둘다 사용될 것이다.

1. 현재 쓰레드의 이름이 다름을 확인해야 하기 때문에 thread.getName()을 해서 출력한다.

2. 현재 로그인 된 사용자의 Princopal 정보는 같아야 하기 떄문에 출력해준다. 

 

@GetMapping("/tests")
@ResponseBody
public Callable<String> testController(){
    log("MVC Inform");
    return new Callable<>() {
        @Override
        public String call() throws Exception {
            log("Callable Inform");
            return "Async Handler";
        }
    };
}

log로 서로 다른 이름을 넣어서 분간이 가능토록 하고 

해당 경로로 로그인후 요청을 넣어보겠다. 

 

 

MVC Inform

this is thread location: http-nio-9090-exec-1
this is principalorg.springframework.security.core.userdetails.User [Username=cksdntjd, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]]

 

Callable Inform


this is thread location:  task-2
this is principal:org.springframework.security.core.userdetails.User [Username=cksdntjd, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]]

 

똑같음을 확인 할 수 있다. 

 

다른 쓰레드를 사용함에도 불구하고 이렇게 같은 응답이 나올 수 있는 것은 .

 

WebAsyncManagerIntegrationFilter 덕분이다. (정확히는 preprocess 덕분이다.)

  • preProcess : Security Context 를 설정. 
  • Callable : 다른 쓰레드이지만 그안에서 동일한 SecurityContext 를 참조 할 수 있다. 
  • PostProcess : SecurityContext 를 정리 하여준다.

 

관련글 더보기

댓글 영역