상황
Spring Security는 인증/인가 프레임워크로, 제공하는 필터들을 상황에 맞게 등록하여 사용할 수 있다. OAuth 인증을 구현하면서, AuthenticationProvider를 만들어서 AuthenticationManager에 등록했는데 해당 로직이 실패했을 때 예외 처리를 해서 적절한 응답을 보내주려고 했다.
문제 1
@ControllerAdvice에 전역 예외 핸들러를 작성하여 해결하려고 했다. 그런데 Spring Security의 필터는 Controller로 들어가기 전에 요청을 검사하므로, 이 방법은 사용할 수 없었다.
해결 1
WebResponseExceptionTranslator를 구현하여 빈으로 등록한다. AuthenticationProvider에서 예외를 던지면, 예외에 포함된 message를 검사해서 응답에 필요한 내용을 추가해주는 방식이다. 참고로 해당 방법은 최신 Spring Security에서는 Deprecated 되었으나, 예외 핸들러를 작성한다는 큰 개념은 변하지 않았다.
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Optional;
public class LoginFailHandle implements WebResponseExceptionTranslator {
...
// 해당 메서드에 OAuth 인증 처리 중 예외가 떨어졌을 때 필요한 로직 구현
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
OAuth2Exception exception = new OAuth2Exception(e.getMessage());
...
// 예외 메세지 검사
}else if("message".equals(e.getMessage())){
status = HttpStatus.CONFLICT;
exception.addAdditionalInformation("resultCode", CODE12345);
}
...
ResponseEntity<OAuth2Exception> cException = new ResponseEntity<>(exception, status);
return cException;
}
}
문제 2
위처럼 로직을 추가해줬음에도, 예외가 발생했을 때 처리되지 않았다. Spring Security에서는 필터가 여러 개 있으면, 기본적으로는 모든 필터를 다 검사해서 하나라도 맞으면 인증을 통과시키는 방식을 취한다. 그래서 예외가 발생해도 다음으로 넘어갔던 것이었다.
해결 2
예외 중에 다음 필터로 넘어가지 않고 바로 로직을 종료하는 예외가 있었다. (InternalAuthenticationServiceException) 해당 예외로 처리해주었다.
...
if(decUid.trim().isEmpty()){
throw new InternalAuthenticationServiceException(ReturnCode.XXX.getCode());
}
...
참고 자료
WebResponseExceptionTranslator (OAuth for Spring Security 2.4.0.BUILD-SNAPSHOT API)
Type Parameters:T - The error model that will be used as the HTTP Response body. All Known Implementing Classes: DefaultWebResponseExceptionTranslator public interface WebResponseExceptionTranslator Translates exceptions into HTTP Responses.
docs.spring.io
Spring Security 인증/인가 예외 JSON 처리
시큐리티 설정을 통해 인증, 인가 설정을 할 수 있다. 이제 이 인증, 인가에 실패했을 경우에 JSON 예외 응답을 보내보자. SecurityConfig.java http.exceptionHandling(e -> e .authenticationEntryPoint(new JwtAuthentication
non-stop.tistory.com
[Spring Security] 예외 처리하기
Notice Spring Boot 3.2.5, Spring Security 6.2.5 기반으로 작성한 글입니다. 아래 포스팅들을 먼저 보면 좋습니다.Spring Security 6 - Architecture → Security Exception 처리하기[Spring Security] 토큰 기반 로그인/로
backend-jaamong.tistory.com
'웹 개발 > Auth' 카테고리의 다른 글
| SSO(Single Sign-On) (0) | 2025.06.11 |
|---|---|
| Basic Auth (0) | 2025.03.20 |
| 로그아웃 처리 된 JWT 토큰 탈취 위험 방지하기(feat. Redis 블랙리스트) (0) | 2025.03.03 |