SecurityContextHolder, Authentication, Principal, UserDetails

알비레오·2025년 9월 8일

자바

목록 보기
16/17

계층구조

SecurityContextHolder
   └─ SecurityContext
        └─ Authentication
             ├─ principal (UserDetails 구현 객체 등)
             ├─ credentials (비밀번호 등)
             └─ authorities (권한 정보)

SecurityContextHolder

  • 인증/ 인가 정보의 저장소(컨테이너) 역할
  • Spring Security가 인증 관련 정보를 ThreadLocal로 저장하여 애플리케이션 어디서나 인증 정보(SecurityContext)를 가져올 수 있게 해줌
  • 현재 사용자의 인증 정보는 다음과 같이 얻을 수 있음
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  • 한 요청의 라이프사이클 동안 동일한 인증 정보가 보장됨

SecurityContext

  • 실제 인증 객체(Authentication)를 담는 컨텍스트 역할
  • SecurityContextHolder가 제공하는 인증 컨텍스트
  • 내부에 Authentication(인증 객체)를 가지고 있음
Authentication auth = SecurityContextHolder.getContext().getAuthentication();

Authentication

  • 인증 정보의 핵심 객체
  • 주로 현재 로그인한 사용자와 그 권한, 인증 상태, 자격 증명 등 보관
  • 주요 필드:
    - principal: 인증된 실제 사용자 정보(Object, 통상 UserDetails)
    • credentials: 자격 정보(주로 비밀번호, 인증 후 null로 처리)
    • authorities: 사용자 권한(roles, authorities)
    • details: 인증 관련 추가 정보
  • 인증 완료 후 사용자 정보, 권한, 이름 등을 가져올 때 Authentication을 참조함

Principal

  • 현재 인증된 사용자 신원 정보
  • Authentication 객체의 principal 필드에 저장됨
  • 일반적으로 UserDetails 객체가 principal로 사용됨
  • 사용자 이름 등 식별 정보를 제공함
    - auth.getPrincipal() 또는 ((UserDetails)auth,getPrincial()),getusername() 등으로 사용

UserDetails

  • Spring Security에서 제공하는 사용자 상세 정보 인터페이스
  • principal의 타입이 되는 것이 일반적
  • 주요 메서드: getUsername(), getPassword(), getAuthorities(), 등
  • DB 등에서 불러온 사용자 정보를 담는 역할
  • 개발자가 커스텀 구현체로 확장하여 사용할 수 있음

0개의 댓글