Tech/Spring

Spring Security 예외 처리

봄의 개발자 2023. 10. 4.
728x90
반응형

스프링 시큐리티로 로그인을 구현하던 중 예외 처리에 대한 이슈가 있었다.

AOP를 통해 공통 관리를 해주려고 했으나 기대했던대로 처리가 되지 않았다.

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class AdminExceptionHandler {
    @ExceptionHandler(AcceptAdminException.class)
    public String handleAcceptAdminException(AcceptAdminException ex, Model model) {
        model.addAttribute("NotAcceptAdmin", ex.getMessage());
        return "/login";
    }

    @ExceptionHandler(NotFoundAdminException.class)
    public String handleNotFoundAdminException(NotFoundAdminException ex, Model model) {
        model.addAttribute("NotFoundAdmin", ex.getMessage());
        return "/login";
    }
}

그래서 찾아보니 Spring Security에서 발생한 예외를 직접적으로 @ExceptionHandler를 사용하여 컨트롤러 어드바이스에서 처리하는 것은 기본적으로는 동작하지 않는다고 했다. Spring Security의 예외는 Spring Security 필터 체인 내에서 처리되기 때문이다.

 

그렇다면 예외 처리는 어떻게 다뤄야할까?

1. 서버 코드

CustomAuthenticationEntryPoint에서 에러 메시지를 설정하고, 리다이렉션을 통해 에러 페이지로 이동하게 된다.

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
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 response, AuthenticationException authException) throws IOException, ServletException {
        // 에러 메시지를 설정하고, 로그인 페이지로 리다이렉션한다.
        request.getSession().setAttribute("loginErrorMessage", "일치하는 회원정보가 없습니다.");
        response.sendRedirect("/login");
    }
}

 

2. 화면단 코드

로그인 페이지에서 타임리프를 사용해 에러 메시지를 출력한다.

<div th:if="${session.loginErrorMessage}">
    <p th:text="${session.loginErrorMessage}" style="color: red;"></p>
</div>

 

이렇게 하면 CustomAuthenticationEntryPoint에서 설정한 에러 메시지가 세션에 저장되고, Thymeleaf를 통해 로그인 페이지에서 출력된다. 이 방법을 통해 Spring Security에서 발생한 예외를 Thymeleaf로 전달하고 처리할 수 있다.

 

728x90
반응형

댓글