AuthenticationManager는 Spring Security에서 인증(authentication) 과정을 담당하는 핵심 인터페이스입니다. 이 컴포넌트는 클라이언트가 제공한 자격 증명을 기반으로 사용자를 인증하고, 인증된 사용자에 대한 정보를 반환하거나, 인증에 실패할 경우 예외를 발생시킵니다.
1. 동작 원리
- 핵심 메소드:
AuthenticationManager는 단 하나의 메소드인
Authentication authenticate(Authentication authentication)
를 정의합니다. 이 메소드는 입력된 Authentication 객체(예: 사용자의 아이디와 비밀번호)를 받아서 인증을 수행합니다. - 인증 과정:
내부적으로 AuthenticationManager는 하나 이상의 AuthenticationProvider를 이용합니다.- 기본 구현체인 ProviderManager는 등록된 여러 AuthenticationProvider 목록을 순회하며, 각 Provider가 주어진 Authentication 객체를 처리할 수 있는지 (supports() 메소드로 확인) 판단합니다.
- 해당 Provider가 처리 가능하면, Provider의 authenticate() 메소드를 호출하여 인증을 시도합니다.
- 만약 Provider 중 하나라도 인증에 성공하면, 인증된 사용자 정보를 포함한 완전한 Authentication 객체를 반환하며, 실패할 경우에는 AuthenticationException을 던집니다.
2. 구현체 및 확장
- ProviderManager:
가장 일반적으로 사용되는 구현체로, 다수의 AuthenticationProvider를 포함할 수 있습니다. 이를 통해 폼 로그인, OAuth, LDAP 등 다양한 인증 방식을 지원할 수 있습니다. - 커스텀 AuthenticationProvider:
필요에 따라 자신만의 인증 로직을 구현할 수 있습니다. 예를 들어, JWT나 API 키 기반 인증을 위해 사용자 정의 AuthenticationProvider를 작성하고, ProviderManager에 등록하면 해당 방식의 인증도 처리할 수 있습니다.
3. 사용 방법
a. Spring Security 필터 체인 내에서 자동 처리
일반적인 Spring Security 설정에서는 AuthenticationManager가 보안 필터 체인 내에서 자동으로 호출됩니다. 예를 들어, 폼 로그인을 설정하면 스프링 시큐리티가 내부적으로 AuthenticationManager를 사용하여 로그인 요청을 처리합니다.
b. 직접 사용하기 (예: 커스텀 로그인 컨트롤러)
특정 상황에서는 AuthenticationManager를 직접 주입받아 사용할 수 있습니다. 아래 예제는 커스텀 로그인 컨트롤러에서 AuthenticationManager를 활용하는 방식입니다.
@RestController
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
// 사용자가 입력한 username과 password로 인증 토큰 생성
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
// AuthenticationManager를 사용하여 인증을 수행
Authentication authentication = authenticationManager.authenticate(authToken);
// 인증 성공 시, 인증된 Authentication 객체를 통해 추가 작업(예: JWT 토큰 생성 등)을 수행
// 예: String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok("인증에 성공했습니다!");
}
}
이 예제에서 사용자는 로그인 요청을 보내고, 해당 요청은 UsernamePasswordAuthenticationToken 형태로 AuthenticationManager에 전달됩니다. AuthenticationManager는 내부의 AuthenticationProvider를 통해 사용자의 자격 증명을 검증한 후, 성공하면 인증된 Authentication 객체를 반환합니다.
4. 요약
- AuthenticationManager의 역할:
클라이언트로부터 받은 인증 정보를 기반으로 사용자 인증을 처리하고, 인증 성공 시 사용자의 상세 정보(권한 등)를 담은 Authentication 객체를 반환합니다. - 동작 메커니즘:
내부적으로 여러 AuthenticationProvider를 순회하면서 인증을 시도하고, 첫 번째로 성공한 Provider의 결과를 반환합니다. - 사용 예:
스프링 시큐리티 설정에서 자동으로 동작하거나, 커스텀 로그인 컨트롤러 등에서 직접 주입받아 사용할 수 있습니다.
이와 같이, AuthenticationManager는 다양한 인증 방식을 유연하게 지원하면서, 보안 관련 로직을 효과적으로 분리 및 관리할 수 있게 도와주는 중요한 컴포넌트입니다.
'Spring > Spring Securitiy' 카테고리의 다른 글
8. Spring AuthenticationProvider 개요 (0) | 2025.02.21 |
---|---|
7. 6.1버전 전에 구현되었던 SecurityConfig 리펙토링 (0) | 2025.02.14 |
6. 인증(Authentication)의 기본 개념과 구조와 Spring Security (0) | 2025.01.23 |
5. Spring Security 6 버전 기준 이전 방식(WebSecurityConfigurerAdapter 사용)과 최신 방식(SecurityFilterChain 사용) 비교 (0) | 2025.01.23 |
4. SecurityConfig 기본 사항 (0) | 2025.01.22 |