AnonymousAuthenticationFilter 목적
해당 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열네 번째에 있다.
AnonymousAuthenticationFilter 는 익명 사용자의 요청에 대해 처리해주는 필터이다.
즉 인증을 하지 않은 요청인 경우 인증 객체를 익명 권한이 들어가 있는 객체를 만들어 SecurityContextHolder에 넣어 주는 역할을 한다.
다르게 말하자면, SecurityContext값이 null 인 경우 Anonymous 값을 넣어주기 위해 사용한다고 볼 수 있겠다.
공식 문서를 살펴보면,
public class AnonymousAuthenticationFilter extends GenericFilterBean implements InitializingBean {
}
와 같은 클래스 구조를 가지고 있으며,
기본 생성자는 아래와 같은 형태이며,
해당 필터에 대한 설명으로 anonymousUser의 이름을 가지며, ROLE_ANONYMOUS 권한을 지닌 사용자을 생성한다고 쓰여있다.
AnonymousAuthenticationFilter(String key)
protected Authentication createAuthentication(javax.servlet.http.HttpServletRequest request)
주요 로직
그리고 이를 사용하여 해당 필터에서는 다음과 같은 로직으로 기능을 수행한다.
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// Step 1: 현재 SecurityContext에 인증 정보가 있는지 확인
if (SecurityContextHolder.getContext().getAuthentication() == null) {
// 인증 정보가 없는 경우의 처리
// Step 2: HTTP 요청을 기반으로 새로운 인증 객체 생성
Authentication authentication = createAuthentication((HttpServletRequest) req);
// Step 3: 새로운 보안 컨텍스트 생성 및 설정
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
// Step 4: 로깅 처리
if (this.logger.isTraceEnabled()) {
// 상세 로깅: 설정된 인증 정보의 전체 내용 출력
this.logger.trace(LogMessage.of(() ->
"Set SecurityContextHolder to " + SecurityContextHolder.getContext().getAuthentication()));
} else {
// 기본 로깅: 간단한 상태 메시지만 출력
this.logger.debug("Set SecurityContextHolder to anonymous SecurityContext");
}
} else {
// Step 5: 이미 인증된 경우의 처리
if (this.logger.isTraceEnabled()) {
// 이미 인증된 경우의 상세 로깅
this.logger.trace(LogMessage.of(() ->
"Did not set SecurityContextHolder since already authenticated " +
SecurityContextHolder.getContext().getAuthentication()));
}
}
// Step 6: 다음 필터로 요청 전달
// 현재 필터의 작업이 완료되면 필터 체인의 다음 필터로 처리를 위임
chain.doFilter(req, res);
}
'Spring > 시큐리티 기본원리' 카테고리의 다른 글
시큐리티 기본 원리( 22 ) - ExceptionTranslationFilter (0) | 2025.01.29 |
---|---|
시큐리티 기본 원리( 20 ) - SecurityContextHolderAwareRequestFilter (0) | 2025.01.28 |
시큐리티 기본 원리( 19 ) - RequestCacheAwareFilter (0) | 2025.01.28 |
시큐리티 기본 원리( 18 ) - BasicAuthenticationFilter (0) | 2025.01.28 |
시큐리티 기본 원리( 17 ) - DefaultLogOutPageGeneratingFilter (0) | 2025.01.28 |
댓글