강의

멘토링

커뮤니티

Inflearn Community Q&A

foodsmith963985's profile image
foodsmith963985

asked

Spring Boot JUnit Testing - Bank Application with Security

Jwt authorization filter implementation and registration completed

로그인 인증 실패 시 예외처리하는 주체는 어느 것인가요?

Resolved

Written on

·

1.5K

·

Edited

0

기존에는 SecurityConfig 클래스의
SecurityFilterChain에서 아래의 코드가
로그인 실패 시 응답을 처리하는 주체였습니다.

 

http.exceptionHandling() // 인증 예외 설정 
        .authenticationEntryPoint((request, response, authenticationException)->{ // 예외 가로채기\
            CustomResponseUtil.fail(response, "로그인을 진행해주세요", HttpStatus.UNAUTHORIZED);
        });


그러다 JwtAuthenticationFilter를 만들면서
attemptAuthentication() 매서드가 실패 시 아래의
unsuccessfulAuthentication()가 실행되게끔 했구요.

@Override 
protected void unsuccessfulAuthentication(HttpServletRequest request,
                                    HttpServletResponse response,
                                    AuthenticationException failed) throws IOException, ServletException {

    CustomResponseUtil.fail(response, "로그인 실패", HttpStatus.UNAUTHORIZED); 
}

 

그래서 헷갈려서 실험해보니 기존의 SecurityFilterChain의 것은 주석처리해도 아무런
상관이 없고, unsuccessfulAuthentication()가
동작하더라구요.

이 두 코드의 차이는 정확히 어떤 것일까요?

spring-bootjunit소프트웨어-테스트

Answer 2

0

metacoding님의 프로필 이미지
metacoding
Instructor

아래의 AI 답변이 정확합니다!!

시큐리티 쪽에서 처리하는 실패 로직은, 인증이 필요한 자원에 접근할 때 발생하는 예외입니다.

내가 직접 로그인하려고 하다가 실패하게 되면

attemptAuthentication -> 실패 ->unsuccessfulAuthentication 가 동작합니다.

0

안녕하세요, 인프런 AI 인턴이에요.

로그인 인증 실패 시 예외처리하는 주체는 SecurityFilterChain이 아니라 AuthenticationEntryPoint 또는 AuthenticationFailureHandler 둘 중 하나입니다. 둘 다 같은 목적으로 사용되는데, 로그인 인증 실패 시 처리할 로직을 구현합니다.

AuthenticationEntryPoint는 인증되지 않은 사용자가 보호된 리소스에 액세스하려고 할 때 호출됩니다. 따라서 이를 이용하여 로그인 인증 실패 시 처리하는 로직을 구현할 수 있습니다.

AuthenticationFailureHandler는 인증을 실패하면 호출됩니다. 로그인 인증 실패 시 처리를 담당하는 Handler입니다.

두 가지 방법 중 하나를 선택하여 사용할 수 있으나 현재 코드에서는 AuthenticationFailureHandler인 unsuccessfulAuthentication() 메서드를 구현하여 실패 시 처리를 구현하였습니다. 따라서 SecurityFilterChain의 코드는 주석처리하여도 문제가 없으며, unsuccessfulAuthentication()가 동작하는 것입니다.

이전 코드에서 AuthenticationEntryPoint를 통해 실패 시 처리하던 로직을 AuthenticationFailureHandler로 옮긴 것으로 보여집니다.

참고로, SecurityFilterChain은 인증, 인가, 보안 등과 관련한 여러 Filter를 순차적으로 실행하는 구성요소입니다.

답변이 도움이 되었길 바랍니다.

foodsmith963985's profile image
foodsmith963985

asked

Ask a question