SecurityContext, SecurityContextHolder

구황작물·2022년 7월 25일
0

Security

목록 보기
4/10

SecurityContext

  • 인증된 사용자의 Authentication객체가 저장되는 보관소로 필요시 언제든 Authentication객체를 꺼내어 쓸 수 있도록 제공되는 클래스

  • ThreadLocal에 저장되어 있어 아무 곳에서나 참고가 가능하도록 설계되어 있다.

인증이 완료되면 HttpSession에 저장되어 어플리케이션 전반에 걸쳐 전역적으로 참고가 가능해진다.

💡클라이언트한테 세션이 response되면 securityContext는 지워진다.

SecurityContextHolder

  • SecurityContext객체를 감싸고 있는 wrapper 클래스이다.
  • 세가지의 방식으로 SecurityContext를 저장한다
    1. MODE_THREADLOCAL : 쓰레드 당 SecurityContext를 할당한다.
    1. MODE_INHERITABLETHREADLOCAL : 메인 쓰레드와 자식 쓰레드에 관하여 동일 한 SecurityContext를 유지한다.
    2. MODE_GLOBAL : 응용프로그램에서 단 하나의 SecurityContext를 저장한다.
  • SecurityContextholder.clearContext() : SecurityContext 기본 정보 초기화 메서드

Authentication authentication = SecurityContextHolder.getContext().getAuthentication() 을 통해 인증 객체를 어디서든 꺼내 쓸 수 있다.

대략적인 흐름

  1. 로그인 시도
  2. Server가 요청을 받아 Therad생성(ThreadLocal할당)
  3. Thread가 인증 처리 시도(인증 객체 생성)
  4. 인증 실패시 SecurityContextHolder.clearContext()로 인증 객체 초기화
  5. 인증 성공시 SecurityContextHolder안의 SecurityContext에 인증 객체 저장
  6. HttpSession에 저장됨
SecurityContext context = SecurityContextHolder.createEmptyContext();
//인증 전 빈 SecurityContext를 만든다.

Authentication auth = new TestingAuthenticationToken("username", "password", "ROLE_USER");
//인증 객체를 생성한다.

context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
//인증 성공시 SecurityContext, SecurityContextHolder에 저장된다.

ThreadLocal : Thread마다 할당된 고유 공간(공유x)
ThreadLocal에 대해 더 자세히알고 싶다면 ->
https://javacan.tistory.com/entry/ThreadLocalUsage

reference : https://catsbi.oopy.io/f9b0d83c-4775-47da-9c81-2261851fe0d0

profile
그냥 개발 좋아하는 덩이뿌리식물

0개의 댓글

관련 채용 정보