OAuth 2.0 html 코드 응답

MoonJaeGyeong·2024년 11월 5일
1

개요


인증 정보가 필요한데, 인증 정보를 넣어주지 않으면 아래와 같이 OAuth 에서 로그인 하라는 식의 html 코드를 보내준다. 근데 내가 원하는 건 해당 처럼 html 을 주는게 아닌 에러 메시지를 띄웠으면 좋겠는데 자꾸 해당 html 코드만 보내준다...

왜 그런지 정확한 이유는 찾을 수 없었지만 API 에서 핸들링하지 못한 에러나 필터 부분에서도 핸들링하지 못한 에러들이 뜨는 경우 위와 같은 html 응답을 보내주는 것 같았다.


Authenticationentrypoint

그래서 이를 해결하기 위해서 Authenticationentrypoint 를 도입하였다.

SecurityConfig.java

  @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            ...
            .exceptionHandling((exceptionHandling) -> exceptionHandling
                .authenticationEntryPoint(authenticationEntryPoint())
            );

        return httpSecurity.build();
    }
    
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new CustomAuthenticationEntryPoint();
    }

CustomAuthenticationEntryPoint.java

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ErrorResponseUtil.sendErrorResponse(response, "요청 혹은 인증 정보에 오류가 있습니다.", HttpServletResponse.SC_UNAUTHORIZED, HttpStatus.UNAUTHORIZED);
    }
}

위와 같이 인증관련 에러가 발생하였을 경우 OAuth 에서 제공하는 로그인 폼을 띄우기 보다는 Json 을 통해 에러가 발생하였다는 응답을 제공할 수 있게 되었습니다.


결론

좀 더 정확한 이유를 찾아보고 싶은데 생각보다 해당 에러처리에 관해 참고할만한 것이 많지 않다. 그래서 해당 블로그 포스팅에 정말 많은 아쉬움이 남는다.. 기회가 된다면 이와 관련한 에러를 다른 사람들은 어떻게 처리하는지 어떻게 작동하는지 알 수 있으면 좋을 것 같다.

profile
내 맘대로 끄적이는 개발 블로그

0개의 댓글

관련 채용 정보