본 내용은 SpringBoot 2.x 기준으로 작성되어 있음

@Slf4j
@RequiredArgsConstructor
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("Authorization Interceptor url: {}", request.getRequestURI());
// WEB, chrome 의 경우 GET, POST OPTIONS = pass
if(HttpMethod.OPTIONS.matches(request.getMethod())) {
return true;
}
// js, html, png resource 를 요청하는 경우 = pass
if(handler instanceof ResourceHttpRequestHandler) {
return true;
}
log.error("허용하지 않음");
return false;
}
}
preHandle() 메서드를 Implements 하여 인증, 인가에 대한 로직을 구현preHandle() 은 Controller 호출 전에 실행되는 메서드postHandle() 은 Controller 호추 후에 실행되는 메서드afterComplete() 메서드는 View 에서 최종 결과가 생성하는 모든 과정이 완료되었을 때 실행되는 메서드@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final AuthorizationInterceptor authorizationInterceptor;
private final List<String> OPEN_API = List.of(
"/open-api/**"
);
private final List<String> DEFAULT_EXCLUDE = List.of(
"/",
"favicon.ico",
"/error"
);
private final List<String> SWAGGER = List.of(
"/swagger-ui.html",
"/swagger-ui/**",
"/v3/api-docs/**"
);
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authorizationInterceptor)
.excludePathPatterns(OPEN_API)
.excludePathPatterns(DEFAULT_EXCLUDE)
.excludePathPatterns(SWAGGER);
}
}
@RequiredArgsConstructor 어노테이션을 통해 Spring 컨테이너에서 가져옴addInterceptors() 메서드를 implements 하여 내부 로직에 AuthorizationInterceptor 객체를 인터셉터로 등록excludePathPatterns() 메서드를 통해 Interceptor 에 영향을 받지 않는 경로 지정 (예: 사용자 인증, 인가가 필요하지 않은 경로)