티스토리 뷰

728x90

인증/인가 API - ExceptionTranslationFilter

ExceptionTranslationFilter는 두 가지 예외를 처리하는 필터이다.

(1) AuthenticationException - 인증 예외 처리

AuthenticationEntryPoint 호출

  • 로그인 페이지 이동, 401 오큐 코드 전달 등

인증 예외가 발생하기 전의 요청 정보를 저장한다.

  • RequestCache - 사용자의 이전 요청 정보를 세션에 저장
  • SavedRequest - 사용자가 요청했던 request 파라미터 값들이나 헤더값들이 저장되어 있다.

(2) AccessDeniedException - 인가 예외 처리

AccessDenideHandler에서 예외 처리하도록 제공한다.

(1) 사용자가 /user에 접근한다.

(2) 인가 예외가 발생하면 AccessDeniedException이 호출되고 AccessDeniedHandler에서 처리가 된다.

(3) 인증 실패는 AuthenticationExcepion이 호출되고 인증 실패 이후의 처리는 AuthenticationEntiryPoint가 처리한다.

이때 SecurityContext에 null값을 처리하는 코드도 있다.

(4) 인증 실패일 때 사용자의 요청 관련 정보를 저장한다. 이전 요청의 URL이나 헤더값들을 저장해논다.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .formLogin()
        .successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                //원래 사용자가 가고자했던 정보를 참조할 수 있음
                HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
                SavedRequest savedRequest = requestCache.getRequest(request, response);
                String redirectUrl = savedRequest.getRedirectUrl();
                response.sendRedirect(redirectUrl);
            }
        });

	//인증 인가 API - ExceptionTranslationFilter
    http
            .exceptionHandling()
            .authenticationEntryPoint(new AuthenticationEntryPoint() {
                @Override
                public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                    response.sendRedirect("/login");
                }
            }) //인가 실패 시 처리
            .accessDeniedHandler(new AccessDeniedHandler() {
                @Override
                public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                    response.sendRedirect("denied");
                }
            });  //인증 실패 시 처리
}

formLogin의 successHandler를 보면 HttpSessionRequestCache를 사용해서 이전 요청했던 주소를 가져올 수 있다.

예를들어 인증이 되어있지 않은 상태에서 mypage를 들어가면 로그인 페이지를 보여주고 로그인하면 이전 mypage를 들어가려고 했던 요청주소로 바로 이동시켜 주는 것이다.

Q&A

SecurityController `/login`과 Security 기본제공 `/login`

더보기

AuthenticationEntryPoint 클래스는 로그인 실패시 호출되는데 이 클래스에서 비즈니스 로직을 구현하게 됩니다. 

일반적으로 인증을 다시 시도할 수 있는 로그인 경로로 이동하게끔 구현합니다.

그렇기 때문에 AuthenticationEntryPoint 에서는 SecurityController 에서 정의한 @GetMapping("/login") 로 이동하는 로직을 구현했기 때문에 해당 메소드를 호출하게 됩니다.

만약 AuthenticationEntryPoint 를 구현하지 않으면 스프링 시큐리티가 기본적으로 제공하는 login 화면으로 이동하게 됩니다. 

즉 AuthenticationEntryPoint 를 통해 login 경로로 이동하도록 구현했다면 이를 받을 수 있는 Controller 를 구현해서 @GetMapping("/login") 와 같은 메소드를 정의해야 합니다.

그렇지 않으면 스프링 시큐리티의 기본 화면으로 이동하게 됩니다.

  • 사용자 인증요청 실패 시
    작성해둔 AuthenticationEntryPoint 를 등록해 두었다면
    Spring Security 기본 인증 URI 보다 `우선적`으로 작동한다

  • AuthenticationEntryPoint 를 통한 Redirect 행위는
    반드시 해당 URI 자원으로 이동할 로직이 있는 Controller 의 URL 로 매핑 한다

  • 위의 두 조건에 해당하지 않는 경우는 , Spring Security 는 기본 제공 URI 를 사용한다

https://www.inflearn.com/questions/35944

참고

https://www.inflearn.com/course/%EC%BD%94%EC%96%B4-%EC%8A%A4%ED%94%84%EB%A7%81-%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0

 

스프링 시큐리티 - Spring Boot 기반으로 개발하는 Spring Security - 인프런 | 강의

초급에서 중.고급에 이르기까지 스프링 시큐리티의 기본 개념부터 API 사용법과 내부 아키텍처를 학습하게 되고 이를 바탕으로 실전 프로젝트를 완성해 나감으로써 스프링 시큐리티의 인증과

www.inflearn.com

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함