SpringSecurity 학습(17) -- SecurityContextHolder, SecurityContext

carlkim·2023년 10월 27일

스프링시큐리티학습

목록 보기
17/24

-- SecurityContext --

  1. Authentication 객체가 저장되는 보관소

  2. 저장소니까 인증 객체를 꺼내어 쓸 수 있도록 제공되는 클래스이다.

  3. SecurityContext 에 Authentication 객체가 저장, Authentication 객체 안에는 user 정보가 저장된다.(인증에 성공하면 생성되는 객체가 user)

  4. ThreadLocal 에 저장된다 아무 곳에서나 참조가 가능하다.
    [ThreadLocal -- 스레드는 스레드마다 고유하게 할당된 저장소가 스레드 로칼이다][스레드간에 공유가 되지 않고 각 스레드에만 접근 가능하다]
    [Security context가 스레드 로칼에 저장되어있어서 어디든 접근 가능]

  5. 인증완료시 HttpSession에 저장되어 어플리케이션 전반에 걸쳐 전역적인 참조 가능.

-- SecurityContextHolder --

  1. SecurityContext를 감싸고 있는 클래스

  2. SecurityContext 객체를 저장하는 방식이 세 가지 모드로 저장하고 있다
    2-1 MODE_THREADLOCAL: 스레드당 SecurityContext 객체를 할당 (기본값
    2-2 MODE_INHERITABLETHREADLOCAL : 메인 스레드와 자식 스레드에 관련한 동일한 SecurityContext를 유지
    2-3 MODE_GLOBAL : 응용 프로그램에서 단 하나의 SecurityContext를 저장한다.

  3. SecurityContextHolder.clearContext() : SecurityContext 기존 정보 초기화

어떤 메소드에서도 다 참조할 수 있게 스프링시큐리티가 작동할 수 있게 지원한다.

Authentication authentication = SecurityContextHolder.getContext().getAuthentication()

로그인 흐름

  1. 사용자가 로그인을 한다

  2. 서버가 로그인 요청을 받는다

  3. 서버는 사용자의 요청을 받은 스레드를 생성한다

  4. 스레드는 ThreadLocal를 할당 받는다

  5. 스레드가 인증처리를 한다(인증필터가 하겠지)

  6. 인증
    6-1 실패시 -> SecurityContextHolder.clearContext()를 실행시킨다

  7. 성공하면 인증필터가 SecurityContextHolder 안에 SecurityContext 안에
    최종적으로 성공한 인증객체를 담는 처리를 한다.

  8. 스레드 로칼이 SecurityContext를 담고 있고

  9. SecurityContext가 HttpSession에 저장이 된다.

profile
기본부터 가면 됩니다.

0개의 댓글