Spring 7기 프로젝트/뉴스피드 팀 프로젝트
Spring SecurityContextHolder
JuNo_12
2025. 5. 26. 17:50
SecurityContextHolder란?
SecurityContextHolder는 현재 실행 중인 스레드(Thread)에 대한 보안 컨텍스트(SecurityContext)를 저장하고 조회하는 역할을 하는 클래스입니다.
- 보안 컨텍스트(SecurityContext)란?
→ 인증 정보(Authentication)와 권한 정보(GrantedAuthority)를 담고 있는 객체입니다. - 쉽게 말해,
- 현재 로그인한 사용자(또는 인증된 사용자)의 정보를 보관하는 저장소(컨테이너)라고 생각하면 됩니다.
왜 필요할까?
웹 요청마다 사용자가 누구인지(인증 상태), 어떤 권한을 가졌는지를 계속 참조해야 하는데,
SecurityContextHolder는 이 정보를 **스레드 로컬(ThreadLocal)**에 저장해서 요청이 처리되는 동안 어디서든 쉽게 접근할 수 있게 해줍니다.
작동 방식 요약
- 인증이 완료되면 (예: 로그인 성공 시)
Authentication 객체가 생성되어 SecurityContext에 저장됩니다. - 그리고 SecurityContext는 다시 SecurityContextHolder에 보관됩니다.
- 요청 처리 중에 언제든 SecurityContextHolder.getContext().getAuthentication()으로 현재 로그인한 사용자의 인증 정보를 꺼내 쓸 수 있습니다.
주요 메서드
- SecurityContextHolder.getContext()
현재 스레드의 보안 컨텍스트를 반환합니다. - SecurityContextHolder.getContext().setAuthentication(Authentication authentication)
인증 정보를 설정합니다. - SecurityContextHolder.clearContext()
현재 스레드의 보안 컨텍스트를 지웁니다 (로그아웃 등에서 사용).
한마디로 정리
SecurityContextHolder는 "현재 로그인한 사용자의 인증 정보를 담아두고, 필요할 때마다 꺼내 쓸 수 있게 해주는 스레드별 저장소"다!