문제 상황
OAuth2를 사용하는 환경에서 로그인 안한 사용자(토큰이 없는)가 권한이 없는 api를 요청할때 403 이 아닌 302 응답을 내려주는 상황
해결
SecurityConfig.java
.exceptionHandling() .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
authenticationEntryPoint를 추가하여 해결하였다.
원인
- 스프링 시큐리티 필터 체인에는 인증 예외 AuthenticationException, 인가 예외 AccessDeniedException 를 처리하는 ExceptionTranslationFilter가 등록되어 있다.
ExceptionTranslationFilter
- 인증 예외 발생
AuthenticationEntryPoint
를 실행한다
- 인가 예외 발생
- 익명(anonymous) 사용자일 경우
AuthenticationEntryPoint
- 익명(anonymous) 사용자가 아닐 경우
AccessDeniedHandler
- 익명 사용자일 경우 인가된 사용자인데 인증이 되지 않은건지 파악할 수 없기 때문
anonymousAuthenticationFilter를 거쳐 익명(anonymous)사용자 권한을 contextHolder에 넣어두었기 때문에 AuthenticationEntryPoint를 타게 된다.