AuthenticationManager

haruceki·2024년 8월 20일

AuthenticationManager는 Spring Security에서 인증(authentication) 과정을 담당하는 핵심 인터페이스이다. 이 인터페이스는 사용자 인증 요청을 받아 처리하고, 인증이 성공적으로 이루어지면 인증된 사용자 정보를 반환한다. 확장 가능하며, 다양한 인증 로직을 구현할 수 있다.
Spring Security 설정에서 AuthenticationManager를 통해 인증 메커니즘을 정의하고, 다양한 인증 방법을 지원할 수 있다.

AuthenticationManager의 역할

  • 인증 처리:
    AuthenticationManager는 사용자가 제출한 인증 정보를 바탕으로 사용자를 인증한다. 이 정보는 일반적으로 Authentication 객체에 담겨 전달된다.
    AuthenticationManager는 인증이 성공하면, 인증된 사용자 정보가 담긴 Authentication 객체를 반환하고, 인증에 실패하면 예외를 던진다.

  • 확장성과 유연성:
    AuthenticationManager는 여러 가지 방식으로 구현할 수 있어, 다양한 인증 방식을 지원한다. 예를 들어, UserDetailsService를 기반으로 하는 인증, LDAP 인증, OAuth2 인증 등을 처리할 수 있다.

주요 메서드:

  • Authentication authenticate(Authentication authentication) throws AuthenticationException 이 메서드는 인증 요청을 받아서 인증을 수행한다.
    파라미터로 전달된 Authentication 객체는 사용자가 입력한 인증 정보(예: 사용자명, 비밀번호 등)를 담고 있다.
    인증에 성공하면, isAuthenticated()가 true로 설정된 Authentication 객체를 반환한다.
    인증에 실패하면 AuthenticationException 예외를 던진다.

AuthenticationManager의 구현체

  • ProviderManager
    AuthenticationManager의 기본 구현체로, 여러 AuthenticationProvider들을 순차적으로 호출하여 인증을 시도한다. 각 AuthenticationProvider는 특정 인증 방식에 대한 로직을 가지고 있으며, ProviderManager는 이를 조합하여 다양한 인증 방법을 지원한다.
public class CustomAuthenticationManager implements AuthenticationManager {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // 사용자 인증 로직
        if ("user".equals(username) && "password".equals(password)) {
            // 인증 성공 시, 인증된 Authentication 객체 반환
            return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
        } else {
            // 인증 실패 시 예외 발생
            throw new BadCredentialsException("Invalid credentials");
        }
    }
}

인증 흐름

  1. 클라이언트가 인증 정보를 제출: 사용자가 로그인 폼이나 API 요청을 통해 사용자명과 비밀번호 등의 인증 정보를 제출.
  2. AuthenticationManager가 인증 요청을 처리: 인증 정보는 Authentication 객체로 감싸진 뒤, AuthenticationManager의 authenticate 메서드로 전달된다.
  3. AuthenticationProvider들이 인증을 시도: AuthenticationManager는 등록된 AuthenticationProvider들을 순차적으로 호출하여, 인증 정보가 유효한지 검증.
  4. 인증 결과 반환: 인증이 성공하면, 인증된 Authentication 객체가 반환되며, 이 객체는 현재 인증된 사용자에 대한 정보를 포함한다. 인증에 실패하면, 적절한 예외가 발생한다.
profile
희망도 절망도 없이 매일 코딩을 한다.

0개의 댓글