반응형
  • [Spring Boot] Spring Security를 사용한 로그인 구현 (Form Login) 여기서 Spring Security를 사용한 로그인을 구현했었음
  • 인증, 인가 실패 시 Spring Security에서 정해진 방식대로 처리했었음
    • 인증 실패 시 401 에러 출력 or 로그인 페이지로 redirect
    • 인가 실패 시 403 에러 출력
  • 인증, 인가 실패 시 내가 원하는 방식으로 처리하고 싶다면 authenticationEntryPoint(인증 실패), accessDeniedHandler(인가 실패)를 사용하면 됨

authenticationEntryPoint, accessDeniedHandler 사용 예제

SecurityConfig

  • 전에 작성한 SecurityConfig의 configure(HttpSecurity http) 메서드에 아래의 코드 추가
http
    .exceptionHandling()
    .authenticationEntryPoint(new MyAuthenticationEntryPoint())
    .accessDeniedHandler(new MyAccessDeniedHandler());
  • 인증에 실패(로그인 하지 않은 경우)하면 MyAuthenticationEntryPoint 호출
  • 인가에 실패(권한이 없는 경우)하면 MyAccessDeniedHandler 호출

MyAuthenticationEntryPoint

public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.sendRedirect("/authentication-fail");
    }
}
  • 인증에 실패 시 /authentication-fail URL로 redirect
  • Controller에서 해당 URL과 인증 실패시 출력될 html을 매핑

MyAccessDeniedHandler

public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.sendRedirect("/authorization-fail");
    }
}
  • 인가에 실패 시 /authorization-fail URL로 redirect
  • Controller에서 해당 URL과 인가 실패시 출력될 html을 매핑

결과

  • 인증 실패 처리 전 (로그인 페이지로 redirect)

  • 인증 실패 처리 후 (인증 실패 출력 페이지로 redirect)

  • 인가 실패 처리 전 (403 에러 출력 페이지)

  • 인가 실패 처리 후 (인증 실패 출력 페이지로 redirect)

추가 - 클래스를 따로 만들지 않고 아래와 같이 익명 클래스로 구현하는 것도 가능

http
    .exceptionHandling()
    .authenticationEntryPoint(new AuthenticationEntryPoint() {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            response.sendRedirect("/security-login/authentication-fail");

        }
    })
    .accessDeniedHandler(new AccessDeniedHandler() {
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
            response.sendRedirect("/security-login/authorization-fail");

        }
    });
반응형

↓ 클릭시 이동

복사했습니다!