221129_광고 관리 플랫폼 대행사 센터 제작 56_커스텀 로그인 페이지 구현

창고·2022년 11월 30일
0

해당 게시글은 개인 프로젝트인 "광고 관리 플랫폼 대행사 센터 제작"
#169 "커스텀 로그인 페이지 구현" 이슈를 다루고 있습니다.

1. 진행 사항

  • SecurityConfig 에서 SecurityChainFilter 메소드를 수정, formLogin().loginPage()를 사용
  • 대부분의 예제가 deprecate된 WebSecurityConfigureAdapter의 configure를 override하는 경우가 많았음
  • 초기에 리디렉션 오류가 계속 발생하였으나 permitAll() 을 하지 않을 경우 리디렉션 오류가 발생한다는 내용을 확인하여 permitAll()을 추가하니 정상 작동
    @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";
    }
}
  • 로그인 실패 시 처리를 위한 AuthFailureHandler를 생성.
    • 외부 레퍼런스를 참고, 에러 발생 시 respose를 로그인 페이지에 반영하여 에러 메시지 출력
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);
    }
}

2. 결과

  • 커스텀 로그인 페이지
  • 로그인 실패 시 (잘못된 비밀번호나 존재하지 않는 ID로 로그인 시)

3. 미흡한 점

  • 외부에서 급하게 템플릿을 가져온 터라 디자인이 엉성함....
  • 존재하지 않는 ID로 접근할 때, PW가 틀렸을 때의 상황을 구분해서 처리를 하지 않아서 추후 개선 필요
profile
공부했던 내용들을 모아둔 창고입니다.

0개의 댓글