본문 바로가기
Spring

[Spring Interceptor] 커스텀 어노테이션과 Intercepter 구현

by 행운의나무 2021. 8. 27.
728x90
반응형

목표 : 커스텀 어노테이션을 만들고, Interceptor에서 어노테이션 여부를 확인한다.

Spring Interceptor

  • Spring 영역 안에서 Controller가 실행 되기 전, 후 처리에 대한 기능들을 적용한다.
  • Spring 영역 안에서 동작하므로, Spring Context 영역에 접근할 수 있다. => Spring Bean 객체에 접근 가능하다.
  • 여러 개의 Interceptor 정의가 가능하다.
    • 로그인 체크, 권한 체크, 실행시간 계산 등의 기능을 처리한다.
  • Interceptor의 실행 메소드
    • preHandler() : Controller 실행 전
    • postHandler() : Controller 실행 후, View Rendering 실행 전
    • afterCompletion() : View Rendering 후

커스텀 어노테이션 생성

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Auth {

}

Controller

@Controller
public class InterceptorController {

    @Auth
    @GetMapping("/auth")
    public ResponseEntity auth(){
        return ResponseEntity.ok().body("auth 어노테이션 존재");
    }

    @GetMapping("/non-auth")
    public ResponseEntity nonAuth(){
        return ResponseEntity.ok().body("auth 어노테이션 없음");
    }
}

Interceptor 구현

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //어노테이션 체크 - Controller에 @Auth 어노테이션이 있는지 확인

        boolean hasAnnotation = checkAnnotation(handler, Auth.class);

        if(hasAnnotation){
            log.info("Auth 어노테이션 확인");
            return true;
        }

        log.info("Auth 어노테이션이 없다.");
        return false;
    }

    private boolean checkAnnotation(Object handler, Class<Auth> authClass) {
        //js. html 타입인 view 과련 파일들은 통과한다.(view 관련 요청 = ResourceHttpRequestHandler)
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        //Auth anntotation이 있는 경우
        if (null != handlerMethod.getMethodAnnotation(authClass) || null != handlerMethod.getBeanType().getAnnotation(authClass)) {
            return true;
        }

        //annotation이 없는 경우
        return false;
    }

}

Interceptor 설정

@RequiredArgsConstructor
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    private final AuthInterceptor authInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor);
    }
}

테스트

쿠팡으로 연결 클릭

 

제주삼다수 그린

COUPANG

www.coupang.com

파트너스 활동을 통해 일정액의 수수료를 제공받을 수 있음

반응형