
이짤이 너무 맘에들어 가져왔습니다.
클라이언트와 서버가 데이터를 주고받을 때, 서로 동일한 출처(origin)에서 통신하는 것이 기본 원칙이다.
여기서 출처란 프로토콜 + 호스트 + 포트 번호로 구성된다.
예를 들어, Spring Boot의 기본 주소인 http://localhost:8080의 경우:
CORS는 이름 그대로 "교차 출처 자원 공유"를 의미하며,
즉 출처가 다른 리소스 사이에서 데이터를 주고받기 위한 규칙을 의미한다.
브라우저는 보안을 위해 기본적으로 서로 다른 출처(origin) 간의 요청을 차단하는데,
이때 필요한 허용 정책이 바로 CORS다.
CORS는 서버가 응답 헤더에 어떤 출처에서의 요청을 허용할지를 명시함으로써,
브라우저가 cross-origin 요청을 허용할 수 있도록 도와주는 역할을 한다.
@Value("${cors.config.allowed-origin}")
private String allowedOrigin;
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin(allowedOrigin);
configuration.addAllowedHeader("*");
ArrayList<String> allowedMethods = new ArrayList<>();
allowedMethods.add("GET");
allowedMethods.add("POST");
allowedMethods.add("PUT");
allowedMethods.add("DELETE");
allowedMethods.add("OPTIONS");
configuration.setAllowedMethods(allowedMethods);
configuration.setAllowCredentials(true); // 인증 인가 설정
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(Customizer.withDefaults())
.csrf(csrf->csrf.disable())
.authorizeHttpRequests(auth->
auth.requestMatchers("/").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
Customizer.withDefaults()은 기본값을 써서 내가 설정한 corsconfig 에 CorsConfigurationSource를 bean등록한걸 사용해라!