본문 바로가기

Language/Spring Security

인증 제공자 - AuthenticationProvider

시큐리티 인증 / 인가 흐름도

  • AuthenticationProvider
    • 사용자의 자격 증명을 확인하고 인증 과정을 관리하는 클래스로서 사용자가 시스템에 액세스하기 위해 제공한 정보(예: 아이디와 비밀번호)가 유효한지 검증하는 과정을 포함
    • 다양한 유형의 인증 메커니즘을 지원할 수 있는데, 예를 들어 표준 사용자 이름과 비밀번호를 기반으로 한 인증, 토큰 기반 인증, 지문 인식 등을 처리 가능
    • 인증 성공 시 Authentication 객체 반환 → 이 객체에는 사용자의 신원 정보와 인증된 자격 증명을 포함
    • 인증 과정 중 문제 발생 시 AuthenticationException과 같은 예외를 발생시켜 문제를 알리는 역할

  • AuthenticationManager로부터 Authentication 객체를 전달 받아 인증 수행
    • 실질적으로 인증 처리를 수행하는 핵심적인 역할을 하는 클래스
  • 인증을 수행할 수 있는 조건인지 검사

AuthenticationProvider 흐름도

  • 인증 성공 ⇒ 완성된 Authentication 객체
  • 인증 실패 ⇒ AuthenticationException 발생

.


AuthenticationProvider 사용 방법 1 - 일반 객체로 생성

→ 순수한 일반 객체(POSO(?))

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
    // 아래 두 방법 모두 동일한 방법
    authenticationManagerBuilder.authenticationProvider(new CustomAuthenticationProvider());
    http.authenticationProvider(new CustomAuthenticationProvider2());

    http
            .authorizeHttpRequests(auth -> auth
                    .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults())
    return http.build();
}

AuthenticationProvider 사용 방법 2 - 빈으로 생성

  • 빈 1개만 정의시

  • 빈 2개이상 정의시

  • 일반 객체로 생성 시 빈을 1개만 정의했을 때 2개이상 정의했을 때와 같은 이슈가 발생하지는 않음
  • 하지만 빈으로 선언하지 않으면 빈을 주입받거나 스프링에서 제공하는 특별한 기능을 사용할 수 없어 일반적으로 빈으로 선언하기에 1개만 정의했을 때와 2개이상 정의했을 때의 차이를 알아둘 것