브라우저에서 보내는 XMLHttpRequest, Fetch API는 Same-Origin Policy(SOP)라는 보안 정책이 적용.
⇒ 브라우저에서 보안을 목적으로, Cross-Origin에 HTTP 요청을 제한하는 정책.
문제 : 인증된 사용자만 사용할 수 있는 API 요청시, CORS 문제 발생.
원인
AccessToken이 담긴 요청만 처리할 수 있도록 Auth Interceptor를 설정함.
AuthInterceptor.class
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 토큰 체크 과정
}
AuthWebConfig.class
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/auth/**", "/car/**", "/archiving/**", "/swagger-ui/**", "/v3/**");
}
Option메서드로 들어오는 Preflight 요청은 해당 인터셉터에서 차단당함.
⇒ CORS발생
Preflight 요청이 들어왔을 때, 바로 통과시켜줄 수 있도록 수정.
AuthInterceptor.class
private final List<String> allowedMethod = List.of("OPTIONS");
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Option메서드로 들어온 요청은 바로 처리될 수 있도록 처리.
if (allowedMethod.contains(request.getMethod())) {
return true;
}
// 토큰 체크 과정
}