반응형

Spring Security에서 AuthenticationException 처리
Spring Security를 사용하면서 인증(Authentication) 과정에서 발생하는 예외를 효과적으로 처리하는 것은 보안 및 사용자 경험 측면에서 매우 중요
AuthenticationException
AuthenticationException은 Spring Security에서 인증 과정 중 발생하는 다양한 예외를 처리하기 위해 제공되는 추상 클래스. 사용자가 잘못된 자격 증명을 제공하거나, 인증이 필요한 리소스에 접근하려고 할 때 발생
주요 하위 클래스
- BadCredentialsException: 잘못된 사용자명 또는 비밀번호 입력 시 발생
- UsernameNotFoundException: 존재하지 않는 사용자명으로 로그인 시 발생
- AccountExpiredException: 계정 만료 시 발생
- CredentialsExpiredException: 비밀번호 유효기간 만료 시 발생
- DisabledException: 비활성화된 계정으로 로그인 시 발생
- LockedException: 계정이 잠긴 상태일 때 발생
AuthenticationEntryPoint
AuthenticationEntryPoint는 인증되지 않은 사용자가 보호된 리소스에 접근할 때 호출되는 인터페이스. 인증이 필요한 요청에 대해 적절한 응답(ex: 401 Unauthorized)을 반환하도록 구현할 수 있음
주요 역할
- 인증되지 않은 요청 감지
- 사용자에게 적절한 에러 메시지 또는 리디렉션 제공
- 보안 이벤트 로깅
처리 동작 과정
- 사용자가 보호된 리소스에 접근 요청을 보냄
- Security Filter Chain을 통해 요청이 인증 여부를 검사
- 인증되지 않은 경우 AuthenticationException이 발생
- AuthenticationEntryPoint가 호출되어 적절한 응답(401 Unauthorized)을 반환
- 사용자는 로그인 페이지로 리디렉션되거나 JSON응답을 받음
더보기
사용자 요청 -> Security Filter Chain -> 인증 실패 -> AuthenticationEntryPoint 호출 -> 응답 반환
구현 예제
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint{
@Override
public void commence(HttpServletRequest request, HttpServletResponse, AuthenticationException authException) throws IOException{
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("{\"message\": \"인증이 필요합니다. 로그인 후 이용해주세요.\"}");
}
}
Security 설정에서 AuthenticationEntryPoint 등록
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
public class SecurityConfig {
private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
public SecurityConfig(CustomAuthenticationEntryPoint customAuthenticationEntryPoint) {
this.customAuthenticationEntryPoint = customAuthenticationEntryPoint;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
}
}
AuthenticationException 처리 커스터마이징(선택)
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<String> handleAuthenticationException(AuthenticationException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("인증 오류: " + ex.getMessage());
}
}
정리
- AuthenticationException은 인증 과정에서 발생하는 다양한 예외들을 다룸
- AuthenticationEntryPoint를 통해 인증되지 않은 요청에 대해 일관된 응답 처리를 할 수 있음
- Spring Security 설정을 통해 AuthenticationEntryPoint를 등록해야 함
- 추가적인 인증 예외 처리를 위해 @ExceptionHandler 활용 가능
- 인증 과정의 동작 흐름을 명확히 이해하면 디버깅 및 보안 강화를 효과적으로 수행할 수 있음
반응형
'IT' 카테고리의 다른 글
| [DB] 데이터베이스 기본 개념 (0) | 2025.02.25 |
|---|---|
| [Spring Boot] Spring Boot 핵심 개념 10가지 (1) | 2025.02.24 |
| [정렬(Sort)] List, Array, Map 정렬 코드(Java) (0) | 2025.01.13 |
| [Test] Mock을 활용한 테스트 코드 작성(Java) (0) | 2024.12.03 |
| [OAuth ,Security] CustomUserDetailsService과 CustomOAuth2UserService 차이점 (1) | 2024.12.02 |