스프링 시큐리티

Ch03. 실전프로젝트(인증 프로세스 Form 인증 구현) - 인증 실패 핸들러(CustomAuthenticationFailureHandler)

webmaster 2022. 1. 19. 12:32
728x90

인증 실패

  • FailureHandler 등록
    • @Component
      public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
      
          @Override
          public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
              String errorMessage = "Invalid Username or Password";
              if(exception instanceof BadCredentialsException){
                  errorMessage = "Invalid Username or Password";
              }else if(exception instanceof InsufficientAuthenticationException){ //userDetail의 data가 올바르지 않을경우
                  errorMessage = "Invalid Secret Key";
              }
              //예외 메시지를 login URL에 파라미터로 전달해 준다.
              setDefaultFailureUrl("/login?error=true&exception=" + errorMessage);
              super.onAuthenticationFailure(request, response, exception);
      
          }
      
      }
    • Exception에 따라 파라미터를 다르게 주어 로그인 화면에 오류를 출력해 줄 수 있다.
  • 파라미터로 받아 화면에 model로 담아서 준다.
  • SecurityConfig
    • 주입받는다.
728x90