Spring-Security

AuthenticationManager & AuthenticationManagerBuilder

neal89 2025. 5. 24. 00:18

1. AuthenticationManager란?

AuthenticationManager는 인증 처리를 담당하는 핵심 인터페이스입니다. 클라이언트(사용자)로부터 전달받은 인증 요청 정보(Authentication 객체, 보통 사용자명과 비밀번호 등)를 받아 인증을 시도합니다.

  • 주요 기능:
    • authenticate(Authentication authentication) 메서드를 통해 인증 시도
    • 인증 성공 시, 완전히 인증된 Authentication 객체 반환
    • 인증 실패 시, AuthenticationException 발생
  • 실제 구현체:
    보통 ProviderManager가 AuthenticationManager 인터페이스를 구현합니다.
    ProviderManager는 여러 AuthenticationProvider를 내부에 관리하며, 전달받은 인증 요청을 적합한 AuthenticationProvider에 위임합니다.

2. AuthenticationProvider와 ProviderManager의 역할

  • AuthenticationProvider는 실제 인증 로직을 수행하는 컴포넌트입니다.
  • 예를 들어, 데이터베이스에서 사용자 정보를 검증하는 DaoAuthenticationProvider, OAuth2 인증을 처리하는 OAuth2AuthenticationProvider 등이 있습니다.
  • ProviderManager는 여러 AuthenticationProvider 목록을 가지고 있고, 인증 요청을 처리할 수 있는 Provider를 찾아 인증을 시도합니다.
  • 만약 여러 AuthenticationProvider가 있고, 첫 번째가 인증을 처리하지 못하면 다음 Provider에게 위임합니다.

3. AuthenticationManagerBuilder란?

AuthenticationManagerBuilder는 AuthenticationManager를 생성하고 설정하는 데 사용되는 빌더(Builder) 클래스입니다.

  • 개발자가 손쉽게 여러 인증 방식을 추가할 수 있도록 유연한 API 제공
  • UserDetailsService를 설정하거나, 커스텀 AuthenticationProvider를 추가하는 등 인증 구성을 단계별로 정의 가능
  • 최종적으로 AuthenticationManager (주로 ProviderManager)를 생성

주요 특징

  • HttpSecurity 설정 시 getSharedObject(AuthenticationManagerBuilder.class)를 통해 빌더 객체를 가져와 인증 방식을 등록할 수 있음
  • AuthenticationManagerBuilder는 빌더 패턴으로 작동하여 최종적으로 완성된 AuthenticationManager를 반환

4. 인증 흐름 예시

  1. 사용자가 로그인 폼이나 HTTP Basic 인증 등으로 인증 정보를 서버에 전송
  2. 이 정보가 Authentication 객체로 변환되어 AuthenticationManager에 전달됨
  3. ProviderManager는 여러 AuthenticationProvider를 순회하며 해당 인증 요청을 처리할 수 있는 Provider를 찾음
  4. 적합한 Provider가 인증을 성공시키면 인증된 Authentication 객체를 반환
  5. 실패하면 AuthenticationException을 던져 인증 실패를 알림

5. 요약

컴포넌트  역할 및 기능
AuthenticationManager 인증 요청을 받아 인증을 시도하는 핵심 인터페이스
ProviderManager AuthenticationManager 구현체, 여러 AuthenticationProvider 관리
AuthenticationProvider 실제 인증 로직 수행 (DB 조회, OAuth2 검증 등)
AuthenticationManagerBuilder AuthenticationManager를 편리하게 생성, 설정하는 빌더 클래스