스프링 시큐리티

Ch02. 스프링 시큐리티 주요 아키텍처 이해 - 인증 저장소(SecurityContextHolder, SecurityContext)

webmaster 2022. 1. 16. 15:37
728x90
  • SecurityContext
    • Authentication 객체가 저장되는 보관소로 필요시 언제든지 Authentication 객체를 꺼내어 쓸 수 있도록 제공되는 클래스
      • SecurityContext > Authentication > User 관계로 저장되어 있다.
    • ThreadLocal에 저장되어 아무 곳에서나 참조가 가능하도록 설계함
      • ThreadLocal : 스레드마다 존재하는 고유 저장소
    • 인증이 완료되면 HttpSession 에 저장되어 애플리케이션 전반에 걸쳐 전역적인 참조가 가능
  • SecurityContextHolder
    • SecurityContext 객체 저장 방식
      • MODE_THREADLOCAL : 쓰레드 SecurityContext 객체를 할당, 기본 값
      • MODE_INHERITABLETHREADLOCAL : 메인 스레드와 자식 스레드에 관하여 동일한 SecurityContext를 유지
      • MODE_GLOBAL :  응용 프로그램에서 단 하나의 SecurityContext를 저장한다.
        • Static으로 저장하여, 메모리에서 단 하나만 존재하고, 참조할 수 있도록 한다.
    • SecurityContextHolder.clearContext() : SecurityContext 기존 정보 초기화
  • Authentication authentication = SecurityContextHolder.getContext(). getAuthentication()
  • 동작 과정

    • 인증이 실패하면 SecurityContext를 초기화한다
    • 인증이 성공하게 되면 SecurityContextHolder안에 SecurityContext에 인증이 성공한 Authentication 객체를 ThreadLocal에 넣어주게 된다.
    • ThreadLocal에 저장된 SecurityContext를 Session에 저장한다.
  • get으로 꺼내오거나 세션에서 꺼내오면 된다.
  • 시큐리티 컨텍스트 모드 변경
    해당 모드로 변경 시, 자식 스레드에도 같은 SecurityContext를 저장한다.
  • 자식쓰레드에도 같은 context를 공유한다.

 

728x90