Spring Security ExceptionHandling

귀찮Lee·2022년 9월 4일
0

Spring Security

목록 보기
12/13
post-thumbnail

◎ Spring Security ExceptionHandling

  • 인증, 인가에서 Error 발생시 후처리를 설정해 줄 필요가 있다.
  • 여러가지 방법이 있지만, 기본적으로 해당 작업을 담당하는 Interface를 구현한 후에 Spring Bean에 넣어서 처리를 하면 된다.

◎ AccessDeniedHandler

  • Spring Security 구조

  • AccessDeniedHandler

    • 인가 예외 처리를 담당
    • 서버에 요청을 할 때 액세스가 가능한지 권한을 체크후 액세스 할 수 없는 요청을 했을시 동작함
  • Spring Security 적용

    @Configuration
    @AllArgsConstructor
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
    public class SecurityConfig {
    
        private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
        private final CustomAccessDeniedHandler customAccessDeniedHandler;
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    
            http.
                    ...
                    .and().exceptionHandling()
                    .authenticationEntryPoint(customAuthenticationEntryPoint)
                    .accessDeniedHandler(customAccessDeniedHandler);
    
            return http.build();
        }
    
        @Bean
        public AccessDeniedHandler accessDeniedHandler() {
            CustomAccessDeniedHandler accessDeniedHandler = new CustomAccessDeniedHandler();
            accessDeniedHandler.setErrorURL("/auth/denied");
    
            return accessDeniedHandler;
        }
    
    }
    @Component
    public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    
        @Setter
        private String errorURL;
    
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
            String deniedUrl = errorURL + "?message=" + accessDeniedException.getMessage();
            response.sendRedirect(deniedUrl);
        }
    }
    @Controller
    @RequestMapping("/auth")
    @RequiredArgsConstructor
    public class SecurityController {
    
        @GetMapping("/denied")
        public ResponseEntity failedSecure(@RequestParam String message){
    
            return new ResponseEntity(
                    new Response(403, message), HttpStatus.NOT_ACCEPTABLE
            );
        }
    
    }

◎ AuthenticationEntryPoint

  • Spring Security 구조 일부

  • AuthenticationEntryPoint

    • 인증이 되지않은 유저가 요청을 했을때 동작함
  • Spring Secutiry 적용

    @Configuration
    @AllArgsConstructor
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
    public class SecurityConfig {
    
        private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
        private final CustomAccessDeniedHandler customAccessDeniedHandler;
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    
            http.
                    ...
                    .and().exceptionHandling()
                    .authenticationEntryPoint(customAuthenticationEntryPoint)
                    .accessDeniedHandler(customAccessDeniedHandler);
    
            return http.build();
        }
    @Component
    public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
                throws IOException, ServletException {
            response.sendRedirect("/auth/not-secured");
        }
    }
    @Controller
    @RequestMapping("/auth")
    @RequiredArgsConstructor
    public class SecurityController {
    
        @GetMapping("/not-secured")
        public ResponseEntity notSecured(){
    
            return new ResponseEntity(
                    new Response(401, "로그인이 되지 않았습니다."), HttpStatus.UNAUTHORIZED
            ); // 권한이 여러개일 경우에는 따로 설정해주어야 한다.
        }
    
    }

◎ 참고 자료

profile
배운 것은 기록하자! / 오류 지적은 언제나 환영!

0개의 댓글