CORS
🌐 CORS
정의
CORS(Cross-Origin Resource Sharing)는 다른 Origin에서 온 요청을 브라우저가 허용할지 결정하는 보안 정책이다.
브라우저는 기본적으로 Same-Origin Policy를 적용한다.
즉, 서로 다른 Origin의 요청은 기본적으로 제한되며, 서버가 허용 정책을 내려줘야 한다.
🧩 주요 설정
- Allowed Origin
- Allowed Method
- Allowed Header
- Allow Credentials
🛠️ 설정 방법
1) 필터를 이용한 방법
- 서블릿 필터에서 CORS 헤더를 직접 추가하는 방식이다.
- 구조가 단순한 프로젝트에서 사용할 수 있다.
- 보통 Spring Security나 공통 필터 체계와 함께 맞춰야 한다.
샘플 소스
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
res.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(request, response);
}
}
2) Config 클래스를 이용한 방법
- Spring에서
CorsConfigurationSource를 정의해 관리하는 방식이다. - 권장 방식이다.
- 유지보수와 설정 일관성이 좋다.
샘플 소스
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;
@Configuration
public class CorsConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOriginPatterns(List.of("http://localhost:5173"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
⚠️ 주의사항
- 인증 정보가 포함된 요청은 허용 Origin을 좁게 설정해야 한다.
- 운영 환경에서는 허용 범위를 너무 넓게 열지 않는 것이 좋다.
Allow-Credentials=true를 사용할 때는*와 함께 쓰지 않도록 주의한다.
댓글남기기