반응형
1) CustomAuthFailureHandler .java
- config파일과 같은 뎁스에 SimpleUrlAuthenticationFailureHandler를 상속한 CustomAuthFailureHandler 생성
- onAuthenticationFailure 오버라이딩
@Component
public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String errorMessage;
if(exception instanceof BadCredentialsException){
errorMessage = "아이디 또는 비밀번호가 맞지 않습니다.";
}else if(exception instanceof InternalAuthenticationServiceException){
errorMessage = "내부 시스템 문제로 요청을 처리할 수 없습니다.";
}else if(exception instanceof UsernameNotFoundException){
errorMessage = "계정이 존재하지 않습니다.";
}else if(exception instanceof AuthenticationCredentialsNotFoundException){
errorMessage = "인증 요청이 거부되었습니다.";
}else {
errorMessage = "알 수 없는 이유로 로그인에 실패하였습니다.";
}
errorMessage = URLEncoder.encode(errorMessage, "UTF-8");
setDefaultFailureUrl("/loginPersonal?error=true&exception=" + errorMessage);
super.onAuthenticationFailure(request, response, exception);
}
}
2) SecurityConfig.java
- config파일에 커스텀 한 failureHandler 등록
private final CustomAuthFailureHandler customAuthFailureHandler;
protected void configure(HttpSecurity http) throws Exception{
http.csrf().disable()
...
.formLogin()
.failureHandler(customAuthFailureHandler)
...
}
3) Controller.java
- error와 exception을 model에 담아 넘겨준다
@GetMapping("/loginPersonal")
public String getLoginPersonal(@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 "loginPersonal";
}
4) Login.jsp
- jstl로 error가 있는경우 화면에 exception을 표시
<div class="errMsg">
<c:if test="${not empty error }" >
<h3><c:out value="${exception }" /></h3>
</c:if>
</div>
반응형
'spring' 카테고리의 다른 글
@RequestParam과 @PathVariable (0) | 2023.08.24 |
---|---|
[SpringSecurity] 필터 (0) | 2023.08.22 |
[Spring Security] Exception (0) | 2023.07.26 |
서버 재기동시 세션 (0) | 2023.02.14 |
Mybatis쿼리문 다중 파라미터 사용 (0) | 2023.02.11 |