스프링 시큐리티/실전프로젝트 - 인증 프로세스 Ajax 인증 구현

ch04. 인증 핸들러 - AjaxAuthenticationSuccessHandler, AjaxAuthenticationFailureHandler

webmaster 2022. 1. 20. 13:22
728x90
  • AjaxAuthenticationSuccessHandler
    • AuthenticationSuccessHandler 인터페이스 구현
    • Response Header 설정
      • response.setStatus(HttpStatus.OK.value());
      • esponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
    • JSON 형식으로 변환하여 인증 객체 리턴 함
      • objectMapper.writeValue(response.getWriter(), ResponseBody.ok(userDto));
    • 
      public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
      
          private ObjectMapper objectMapper = new ObjectMapper();
      
          @Override
          public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
              Account account = (Account)authentication.getPrincipal();//인증 성공한 객체가 있다
              response.setStatus(HttpStatus.OK.value());
              response.setContentType(MediaType.APPLICATION_JSON_VALUE);
      
              objectMapper.writeValue(response.getWriter(), account);
          }
      }
      
  • AjaxAuthenticationFailureHandler
    • AuthenticationFailureHandler 인터페이스 구현
    • Response Header 설정
      • response.setStatus(HttpStatus.UNAUTHORIZED.value());
      • response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    • JSON 형식으로 변환하여 오류 메시지 리턴 함
      • objectMapper.writeValue(response.getWriter(), ResponseBody.error(message));
    • public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
          private ObjectMapper objectMapper = new ObjectMapper();
      
          @Override
          public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
              String errMsg = "Invalid Username or Password";
              response.setStatus(HttpStatus.UNAUTHORIZED.value());
              response.setContentType(MediaType.APPLICATION_JSON_VALUE);
      
              if(exception instanceof BadCredentialsException){
                  errMsg = "Invalid Username or Password";
              }else if(exception instanceof DisabledException){
                  errMsg = "Locked";
              }else if(exception instanceof CredentialsExpiredException){
                  errMsg = "Expired password";
              }
      
              objectMapper.writeValue(response.getWriter(), errMsg);
          }
      }​
  • 기존에 동작했던 Handler와 비슷하지만 Statuscode와 Json형태로 반환하는 점만 다르다.
  • bean 등록
    • Filter에 등록

 

728x90