해당 게시글은 개인 프로젝트인 "광고 관리 플랫폼 대행사 센터 제작" 중
#169 "커스텀 로그인 페이지 구현" 이슈를 다루고 있습니다.
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll()
.anyRequest().authenticated()
)
.formLogin() // loginPage()~permitAll() 까지 추가
.loginPage("/agency/login")
.loginProcessingUrl("/agency/login")
.defaultSuccessUrl("/clients", true)
.failureHandler(authenticationFailureHandler())
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/")
.and()
.csrf().disable() // csrf().disable() 추가
.build();
}
....
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return new CustomAuthFailureHandler();
}
@RequiredArgsConstructor
@RequestMapping("/agency")
@Controller
public class AgencyController {
@RequestMapping(value={"/", "/login"}, method = {RequestMethod.GET, RequestMethod.POST})
public String loginGet(Model model) {
return "agency/login";
}
}
public class CustomAuthFailureHandler implements AuthenticationFailureHandler {
private final String DEFAULT_FAILURE_URL = "/agency/login?error=true";
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
String errorMessage = null;
if (exception instanceof BadCredentialsException || exception instanceof InternalAuthenticationServiceException) {
errorMessage = "아이디나 비밀번호가 맞지 않습니다. 다시 확인해주십시오.";
}
else {
errorMessage = "알 수 없는 이유로 로그인에 실패하였습니다. 관리자에게 문의하십시오.";
}
request.setAttribute("errorMessage", errorMessage);
request.getRequestDispatcher(DEFAULT_FAILURE_URL).forward(request, response);
}
}