> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/framework/spring-boot/rest-api/sop-cors.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# SOP와 CORS

## 1. SOP(Same-Origin Policy)

**브라우저의 보안 정책**으로, **프로토콜/도메인/포트**가 모두 같아야 동일 출처로 간주한다

* 서버-서버 통신에는 적용되지 않고 **브라우저-서버 통신시 브라우저에서 이를 보안상의 이유로 막는 것.**
  * PostMan을 통한 요청은 브라우저를 사용한 요청이 아니므로 CORS에 걸리지 않는다.
* 만약, 셋중 하나라도 다르다면, JS로 다른 출처의 리소스를 읽어 오는 것을 차단한다.

## 2. CORS(Cross-Origin Resource Sharing)

**서버가**  응답 헤더로  “이 **출처(Origin)**&#xC5D0;서 오는 요청은 읽어도 된다”고 **브라우저에게 허용을 선언하는 메커니즘.**

### 1) CORS로 설정 가능한 옵션들

* `Access-Control-Allow-Origin` (허용할 Origin)
* `Access-Control-Allow-Methods` (허용할 메서드)
* `Access-Control-Allow-Headers` (허용할 요청 헤더)
* `Access-Control-Allow-Credentials` (쿠키/인증정보 전송 허용)

***

## 2. Web MVC 전역 CORS 설정 예시

```java
@Configuration
public class WebMvcCorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")                 // 어떤 경로에 적용할지
                .allowedOrigins("https://my-frontend.example.com")
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("X-Total-Count")
                .allowCredentials(true)                // 쿠키/세션 사용 시
                .maxAge(3600);
    }
}
```

**장점**

* 중앙집중 관리, API 스펙 변화 대응 쉬움

**주의**

* **Spring Security가 활성화된 경우**, Security의 CORS 설정이 우선된다.

***

## 3. Spring Security 적용 후 CORS 설정 예시

* Security 필터 체인으로 들어오는 요청은 **Security가 CORS를 직접 처리**하도록 해야 함.

```java
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // CORS를 Security에서 처리
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            // CSRF는 SPA+API 구조에서 비활성화하는 경우가 흔함(상황에 맞게 결정)
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**", "/actuator/**").permitAll()
                .anyRequest().authenticated()
            );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        // 허용 Origin — 자격 증명(쿠키 등)과 함께 사용 시 반드시 구체 도메인 지정
        config.setAllowedOrigins(List.of("https://my-frontend.example.com"));
        // 또는 최신 스펙의 패턴 사용: config.addAllowedOriginPattern("https://*.example.com");

        config.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS"));
        config.setAllowedHeaders(List.of("*"));
        config.setExposedHeaders(List.of("X-Total-Count"));
        config.setAllowCredentials(true); // 세션/쿠키 허용 -> true인경우 allowedOrigins에 * 불가.
        config.setMaxAge(3600L);          // Preflight 캐시

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 특정 경로 매핑
        source.registerCorsConfiguration("/api/**", config);
        // 모든 경로에 일괄 적용하려면 "/**"
        return source;
    }
}
```
