GitHub

https://github.com/Backcoder-June

BackCoder 기록 그리고 숙달

Back to the Spring

[Spring Security] Authentication Failure Handler 적용

Backcoder 2022. 12. 24. 22:48

Spring Security 에서는 로그인 성공 / 실패시, 

SecurityConfig 에서 특정 URL 로 리다이렉트 시키거나 

Handler 를 활용해 후처리를 해줄 수 있습니다.

 

[ SecurityConfig ]

.defaultSuccessUrl("/allboard")
@Autowired
AuthenticationFailureHandler authenticationFailureHandler;
.failureHandler(authenticationFailureHandler)

 

Handler 를 이용하고자 하면 

(1) AuthenticationFailureHandler 인터페이스를 implements 해서 사용하거나 

(2) SimpleUrlAuthenticationFailureHandlerextends 하고 

 

onAuthenticationFailure 메소드를 오버라이딩 해서 => 실패했을 시의 후처리를 해줄 수 있습니다.

(2) 번 방법을 사용할 경우, DefaultFailureUrl 까지 지정해 줄 수 있습니다. 

 

 

(2) 번을 사용해서 로그인 실패 시 URL을 정해줌과 동시에, Parameter 로 Exception 메세지를 담아 보내고 

Controller 에서 메세지가 담긴 파라미터를 받아 View 에 뿌려주는 방식으로 진행했습니다.

 

[ extends SimpleUrlAuthenticationFailureHandler ] 

@Component
public class DomainFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        String errorMessage = getExceptionMessage(exception);

        errorMessage = URLEncoder.encode(errorMessage, StandardCharsets.UTF_8); /* 한글 인코딩 */
        setDefaultFailureUrl("/login?error=true&exception=" + errorMessage);
        super.onAuthenticationFailure(request, response, exception);
    }

    private String getExceptionMessage(AuthenticationException exception) {
        if (exception instanceof BadCredentialsException) {
            return "아이디 또는 비밀번호가 일치하지 않습니다.";
        } else if (exception instanceof UsernameNotFoundException) {
            return "계정정보가 없습니다.";
        } else {
            return "잘못된 로그인 시도입니다. 아이디를 확인해 주세요.";
        }
    }
}

 

[ Controller ] 

@GetMapping("/login")
public String loginHome(@RequestParam(value = "error", required = false) String error,
                        @RequestParam(value = "exception", required = false) String exception,  Model model) {
    model.addAttribute("error", error);
    model.addAttribute("exception", exception);
    return "member/login";
}

 

[ View - JSP ] 

<c:if test="${param.get('error')}">
  <div id="loginFailMessage">
      ${exception}
  </div>
</c:if>