Spring Interceptor 구현

성현·2024년 6월 27일
0

Spring Interceptor

목록 보기
2/3

Spring Interceptor를 냅다 사용해보는 시간이다.
냅다 사용해 본 후 궁금한 내용들을 파헤칠 것이다.

[사용 목표]
특정 컨트롤러로 접근 시 DB에 해당 사용자 계정이 있는지 확인.

1. 커스텀 어노테이션 구현

//빈 껍데기 어노테이션을 만들어준다.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auth {

}

2. HandlerInterceptor 구현

먼저, HandlerInterceptor 구현체를 만들어 인터셉터를 구현해준다.
나는 Controller호출 전 처리를 구현할거기 때문에 preHandle만 구현해주었다.

주요 로직

  • HandlerMethod handlerMethod= (HandlerMehotd) handler; //HandlerMethod handlerMethodHandlerMethod 가지고 오기
  • Auth auth = handlerMethod.getMethodAnnotation(Auth.class); // auth 어노테이션 확인
  • if(auth == null) true; // auth 어노테이션이 안붙은 컨트롤러는 인터셉터 타지 않음

    3. WebMvcConfigurer 구현


    주요로직

  • InterceptorRegistgry registry에 구현한 Interceptor등록

    4. 결과확인

    [부팅로그]

    [10:46:01.214] INFO [org.springframework.security.web.DefaultSecurityFilterChain.<init>:55] - Will secure any request with [org.springframework.security.web.session.DisableEncodeUrlFilter@14e6a2ed
     (생략)
    [10:46:02.078] INFO [com.kosaf.core.config.interceptor.AuthInterceptor.addInterceptors:17] - 언제호출? AuthInterceptor
     

    위 로그에서 확인할 수 있듯이, 각종 filter등록이 끝나면 interceptor도 등록한다.

    [controller 진입 요청]

     [10:46:12.320]INFO [com.kosaf.core.config.interceptor.UserAuthInterceptor.preHandle:25]
     - handler..? com.kosaf.core.web.replaceKeyword.presentation.ReplaceKeywordController#replaceKeyword()

    진입 요청 이후에는 내가 2번에서 만든 HandlerInterceptor 구현체의 preHandle로 들어오는 것을 확인할 수 있다.

  • profile
    행동하는 사람

    0개의 댓글