✅ 전략 패턴이란
- 알고리즙을 캡슐화하여 런타임에 알고리즘을 바꾸거나 선택할 수 있도록 하는 디자인 패턴
✅ 스프링 시큐리티에서의 전략 패턴 구성
| 구성 요소 |
역할 |
전략 패턴에서의 역할 |
AuthenticationManager |
인증 요청을 처리하는 진입점 |
Context |
AuthenticationProvider |
인증 방법을 정의 (DB, LDAP, JWT 등) |
Strategy 인터페이스의 구현체 |
Authentication |
인증 정보 (id/password or token) |
알고리즘 입력/출력 값 객체 |
✅ 동작 흐름
- 사용자가 로그인 폼 제출
- SecurityFilterChain → UsernamePasswordAuthenticationFilter 실행
- 입력한
ID/PW 기반으로 Authentiction(UsernamePasswordAuthenticationToken) 객체 생성
- 해당 객체를
AuthenticationManager.authenticate() 전달
- AuthenticationManager는 등록된 여러 AuthenticationProvider 중 지원 가능한 것을 찾기 위해
supports() 확인
- 해당 AuthenticationProvider가
authenticate()를 실행하여 인증 성공/실패 판단
- 성공 시 인증된 Authentication 객체를 반환하고
SecurityContextHolder(by thread-local)에 저장
✅ 코드 예시
public class ProviderManager implements AuthenticationManager {
private List<AuthenticationProvider> providers;
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
for (AuthenticationProvider provider : providers) {
if (provider.supports(auth.getClass())) {
return provider.authenticate(auth); // 전략 선택 및 실행
}
}
throw new ProviderNotFoundException("No provider found for " + auth.getClass());
}
}