Origin을 담아 전달Origin: https://does.com
Access-Control-Allow-Origin을 담아 클라이언트로 전달Access-Control-Allow-Headers, Access-Control-Allow-Methods가 있다.
Origin과 서버가 보내준 Access-Control-Allow-Origin을 비교Access-Control-Max-Age 헤더를 통해 캐시될 시간을 명시하면 예비 요청을 캐싱 시켜 그 다음 요청부터 본 요청을 바로 보내도록 최적화를 시킬 수도 있다.GET, HEAD, POST 중 하나여야 한다.Accept, Accept-Language, Content-Language, Content-Type, DPR, Downlink, Save-Data, Viewport-Width, Width 헤더일 경우 에만 적용된다.Content-Type 헤더가 application/x-www-form-urlencoded, multipart/form-data, text/plain중 하나여야한다.일반적으로 Rest API 방식으로 Json 데이터를 주고 받는 경우가 많기에 Preflight 방식이 대부분 사용된다고 보면 된다.
Credential)를 실어 요청할때 사용되는 요청 (쿠키, 헤더의 토큰 등)withCredentials: trueAccess-Control-Allow-Credentials 항목을 true로 설정해야 한다.Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers의 값에 와일드카드 문자("*")는 사용할 수 없다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080", "http://localhost:8081")
.allowedMethods("GET", "POST")
.allowCredentials(true)
.maxAge(3000);
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.cors()
.configurationSource(corsConfigurationSource())
// ...
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowedOriginPatterns(List.of(corsAllowedOrigins.split(",")));
corsConfig.setAllowedMethods(List.of("HEAD","POST","GET","DELETE","PUT", "OPTIONS"));
corsConfig.setAllowedHeaders(List.of("*"));
corsConfig.setAllowCredentials(true);
corsConfig.setExposedHeaders(List.of(HttpHeaders.LOCATION, HttpHeaders.SET_COOKIE));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig);
return source;
}
curl \
--verbose \
--request OPTIONS \
'http://localhost:8080/api/test' \
--header 'Origin: http://localhost:3000' \
--header 'Access-Control-Request-Headers: Origin, Accept, Content-Type' \
--header 'Access-Control-Request-Method: DELETE'
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://inpa.tistory.com/entry/WEB-%F0%9F%93%9A-CORS-%F0%9F%92%AF-%EC%A0%95%EB%A6%AC-%ED%95%B4%EA%B2%B0-%EB%B0%A9%EB%B2%95-%F0%9F%91%8F#%F0%9F%92%AC_%EA%B2%B0%EA%B5%AD_cors_%ED%95%B4%EA%B2%B0%EC%B1%85%EC%9D%80%EC%84%9C%EB%B2%84%EC%9D%98%ED%97%88%EC%9A%A9%EC%9D%B4_%ED%95%84%EC%9A%94