콘텐츠로 이동

2022 07 31

2022-07-31

Interceptor

  • vs Filter
    1. 호출 시점
      • Filter: DispatcherServlet 실행 전
      • Interceptor: DispatcherServlet 실행 후
    2. 설정 위치
      • Filter: web.xml
      • Interceptor: spring-servlet.xml
    3. 구현 방식
      • Filter: web.xml
      • Interceptor: 메서드 구현 필요
  • 구현 방식
    • HandlerInterceptor 인터페이스 구현
      • preHandle() : 컨트롤러가 호출되기 전에 실행
      • postHandle() : 컨트롤러가 실행된 후에 호출
      • afterCompletion() : 뷰까지 최종 결과 생성하고 실행
      • 각 메서드에서 true 반환시 다음 체인 실행
        • false 반환시 남은 인터셉터/컨트롤러 실행 X
    • HandlerInterceptorAdapter 클래스 상속
      • postHandle(), afterCompletion() 구현되어있음
      • preHandle() 만 뚝딱 구현
  • 어노테이션으로 접근 권한 조절

    • 어노테이션 만들기
      @Retention(RUNTIME)
      @Target(METHOD)
      public @interface Auth {
      }
      
    • 인터셉터 만들기
      public class AuthInterceptor extends HandlerInterceptorAdapter {
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
              // 1. handler 종류 확인
              if (!(handler instanceof HandlerMethod)) {
                  return true
              }
      
              // 2. 형 변환
              HandlerMethod handlerMethod = (HandlerMethod) handler;
      
              // 3. @Auth 받아오기
              Auth auth = handlerMethod.getMethodAnnotation(Auth.class);
      
              // 4. method에 @Auth가 없다면, 인증이 필요없다는 뜻
              if (Objects.isNull(auth)) {
                  return true;
              }
      
              // 5. @Auth가 있는 경우라면 토큰 체크
              // 6. 접근 허가
          }
      }
      
    • WebMvcConfigurer 등록
      @Configuration
      @RequiredArgsConstructor
      public class AuthWebMvcConfig implements WebMvcConfigurer {
      
          private final JwtProvider jwtProvider;
      
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
              registry.addInterceptor(authInterceptor());
          }
      
          @Bean
          public AuthInterceptor authInterceptor() {
              return new AuthInterceptor(jwtProvider);
          }
      }