스프링 COPS 정책 변경

백엔드&인프라 추종자·2025년 3월 10일

스프링 공부

목록 보기
26/35

Spring에서 @CrossOrigin 어노테이션을 사용하여 여러 개의 도메인을 지정하는 방법은 다음과 같습니다.


1️⃣ 개별 컨트롤러에 설정하는 방법

@CrossOrigin 어노테이션의 origins 속성에 여러 개의 도메인을 배열로 지정할 수 있습니다.

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = {"https://example.com", "https://another.com"})
public class SampleController {

    @GetMapping("/data")
    public String getData() {
        return "Hello, CORS!";
    }
}

📌 특징:

  • 특정 컨트롤러에만 CORS 설정을 적용합니다.
  • origins 속성에 여러 개의 도메인을 배열로 입력하면 해당 도메인만 허용됩니다.

2️⃣ 특정 엔드포인트에 설정하는 방법

메서드 단위에서 @CrossOrigin을 설정할 수도 있습니다.

@RestController
@RequestMapping("/api")
public class SampleController {

    @CrossOrigin(origins = {"https://example.com", "https://another.com"})
    @GetMapping("/data")
    public String getData() {
        return "Hello, CORS!";
    }
}

📌 특징:

  • 특정 엔드포인트(/api/data)에 대해서만 CORS를 설정할 수 있습니다.
  • 컨트롤러 전체가 아닌 개별 메서드에 적용하고 싶을 때 사용합니다.

3️⃣ 전역적으로 설정하는 방법 (WebMvcConfigurer 사용)

Spring Boot 애플리케이션 전체에 CORS 설정을 적용하려면 WebMvcConfigurer를 사용해야 합니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("https://example.com", "https://another.com")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*");
            }
        };
    }
}

📌 특징:

  • 애플리케이션 전체에 CORS 설정을 적용할 수 있습니다.
  • 여러 개의 도메인을 allowedOrigins 속성으로 지정합니다.
  • 특정 HTTP 메서드(GET, POST, PUT, DELETE 등)를 허용할 수도 있습니다.

4️⃣ Spring Security를 사용하는 경우

Spring Security가 적용되어 있으면, Security 설정에서도 CORS를 허용해야 합니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .cors() // CORS 설정 허용
            .and()
            .csrf().disable()
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().permitAll()
            );

        return http.build();
    }
}

📌 특징:

  • Spring Security가 있을 경우 cors() 설정을 추가해야 합니다.
  • WebMvcConfigurer에서 설정한 CORS 정책이 정상적으로 동작하도록 보장합니다.

🔥 결론

  • 특정 컨트롤러 또는 메서드에만 적용하려면? 👉 @CrossOrigin
  • 애플리케이션 전체에 적용하려면? 👉 WebMvcConfigurer
  • Spring Security와 함께 사용한다면? 👉 SecurityFilterChain에서 cors() 추가

애플리케이션의 요구사항에 맞게 적절한 방법을 선택하면 됩니다. 🚀

profile
AI 답변 글을 주로 올립니다.

0개의 댓글