티스토리 뷰

🍀 Spring Boot

Spring Security에서 CORS 설정

James Wetzel 2025. 2. 9. 20:09
728x90
반응형

1. 모든 도메인 허용 (*)

모든 도메인에서 요청을 허용하려면 setAllowedOrigins(List.of("*"))을 사용할 수 있습니다.
하지만, setAllowCredentials(true)와 함께 사용할 수 없습니다.
즉, setAllowCredentials(true)를 설정한 상태에서 setAllowedOrigins("*")을 사용하면 Spring Boot가 예외를 발생시킵니다.

configuration.setAllowedOrigins(List.of("*")); // 모든 도메인 허용
configuration.setAllowCredentials(false); // credentials 허용 비활성화

🔹 장점:

  • 빠른 테스트 및 제한 없는 접근이 가능
  • 공용 API에서 사용할 수 있음

🔹 단점:

  • 보안 취약점 (모든 사이트에서 요청 가능)
  • 인증 정보를 포함한 요청이 불가능 (setAllowCredentials(true) 사용 불가)

2. 여러 개의 특정 도메인 허용

List.of("도메인1", "도메인2", "도메인3") 형식으로 여러 개의 도메인을 설정할 수 있습니다.

configuration.setAllowedOrigins(List.of("http://localhost:3000", "https://mydomain.com", "https://api.example.com"));
configuration.setAllowCredentials(true); // 인증 정보 포함 요청 허용

🔹 장점:

  • 특정 도메인에서만 API 요청 허용
  • 보안 강화
  • setAllowCredentials(true) 사용 가능 (인증 포함 요청 가능)

🔹 단점:

  • 새 도메인을 추가하려면 매번 코드 수정이 필요

3. 동적 CORS 설정 (예: 데이터베이스에서 도메인 목록을 가져오기)

만약 허용할 도메인을 코드에서 직접 관리하는 것이 아니라 데이터베이스나 환경 변수에서 불러와서 설정하고 싶다면, 다음과 같이 동적으로 설정할 수도 있습니다.

// 환경 변수 또는 데이터베이스에서 허용할 도메인 목록을 가져온다고 가정
List<String> allowedOrigins = getAllowedOriginsFromDatabaseOrEnv(); 

configuration.setAllowedOrigins(allowedOrigins);
configuration.setAllowCredentials(true);

🔹 장점:

  • 유연한 관리 (도메인을 DB에서 추가/삭제 가능)
  • 코드 수정 없이 도메인 변경 가능

🔹 단점:

  • 데이터베이스 연결이나 설정 로직 추가 필요

4. 특정 패턴의 도메인 허용 (setAllowedOriginPatterns)

만약 서브도메인을 포함한 특정 패턴의 도메인만 허용하고 싶다면, setAllowedOrigins() 대신 setAllowedOriginPatterns()을 사용할 수 있습니다.

configuration.setAllowedOriginPatterns(List.of("https://*.example.com")); // 모든 서브도메인 허용
configuration.setAllowCredentials(true);

🔹 예제:

🔹 장점:

  • 특정 도메인의 모든 서브도메인 허용 가능
  • 보안 유지

🔹 단점:

  • setAllowedOrigins()보다 덜 직관적

최종 코드 예제

아래는 여러 개의 특정 도메인을 허용하면서, 인증 정보를 포함한 요청(setAllowCredentials(true))을 허용하는 최적의 설정 예제입니다.

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    
    // 여러 개의 특정 도메인 허용
    configuration.setAllowedOrigins(List.of(
            "http://localhost:3000", 
            "https://mydomain.com", 
            "https://api.example.com"
    ));

    // 인증 정보를 포함한 요청 허용 (Authorization 헤더 등 포함 가능)
    configuration.setAllowCredentials(true);
    
    // 허용할 HTTP 메서드
    configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    
    // 허용할 요청 헤더
    configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
    
    // CORS 정책을 적용할 경로 설정
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    
    return source;
}

결론

방법 사용법 setAllowCredentials(true) 사용 가능? 보안 수준

모든 도메인 허용 setAllowedOrigins(List.of("*")) ❌ (불가능) 🔴 낮음
여러 도메인 허용 setAllowedOrigins(List.of("도메인1", "도메인2")) ✅ (가능) 🟢 높음
동적 도메인 설정 setAllowedOrigins(getFromDatabase()) ✅ (가능) 🟢 높음
특정 패턴 허용 setAllowedOriginPatterns(List.of("https://*.example.com")) ✅ (가능) 🟡 중간

실무에서는 특정 도메인만 허용하는 방식 (setAllowedOrigins(List.of("도메인1", "도메인2")))을 권장합니다.
특정 서브도메인을 허용하려면 setAllowedOriginPatterns()을 사용할 수 있습니다.
테스트 환경에서만 setAllowedOrigins(List.of("*"))을 사용할 수 있지만, 실제 운영 환경에서는 보안 문제로 추천되지 않습니다.


이제 CORS 설정을 보안성 있게 적용할 수 있습니다! 😊
더 궁금한 점이 있으면 언제든지 질문해주세요. 🚀

728x90
반응형