Java/Spring Boot

[java spring boot] cors 허용하는 방법

너무 궁금해 2025. 3. 18. 09:48

📢 [java spring boot] cors 허용하는 방법

📌 REST API를 통해 다른 서버의 데이터에 접근하는 경우 CORS(Cross-Origin Resource Sharing) 정책 위반 문제로 오류가 발생할 수 있습니다. 

📌 크롬의 개발자 도구에서 확인하면 아래와 같은 오류를 확인할 수 있습니다.
Access to XMLHttpRequest at '데이터 제공 도메인' from origin '데이터 요청 도메인' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

📌 데이터 제공 서버에 설정을 통해 문제를 해결할 수 있습니다.


📝 Controller에서 개별적으로 CORS 설정하기

🙌 특정 컨트롤러 또는 메서드에만 CORS를 허용하고 싶다면, @CrossOrigin 애너테이션을 사용하면 됩니다.

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

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://example.com", allowedHeaders = "*") // 특정 도메인 허용
public class SampleController {

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

    @PostMapping("/submit")
    @CrossOrigin(origins = "http://anotherdomain.com") // 특정 메서드에만 허용
    public String submitData(@RequestBody String data) {
        return "Received: " + data;
    }
}

 

📝 전역 CORS 설정

🙌 Spring Security를 사용하지 않거나, 단순한 CORS 설정이 필요한 경우 WebMvcConfigurer를 이용할 수 있습니다.

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

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 모든 엔드포인트에 대해 CORS 적용
                .allowedOrigins("http://example.com") // 허용할 도메인
                // 여러 Origin을 허용하려면 ,로 구분
                // allowedOrigins("*") → 모든 도메인 허용 (보안상 위험할 수 있음)
                // allowCredentials(true) 사용 시, allowedOrigins("*")를 사용할 수 없음
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 HTTP 메서드
                .allowedHeaders("*") // 모든 헤더 허용
                .allowCredentials(true); // 쿠키 인증 허용
    }
}

또는, 

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

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {

            @Override
            public void addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry registry) {
                registry.addMapping("/**")
                    .allowedOrigins("http://example.com")
                    .allowedMethods("GET", "POST", "PUT", "DELETE")
                    .allowedHeaders("*");
            }
        };
    }
}

이런 식으로도 가능합니다.

 

📝 Spring Boot 설정 파일 (application.yml)로 CORS 설정

🙌 Spring Boot 2.4 이상에서는 application.yml에서도 CORS 설정을 할 수 있지만, WebMvcConfigurer나 SecurityConfig보다 세부적인 설정이 어렵습니다.

spring:
  web:
    cors:
      allowed-origins: "http://example.com"
      allowed-methods: "GET,POST,PUT,DELETE"
      allowed-headers: "*"
      allow-credentials: true



📝 Spring Security와 함께 글로벌 CORS 설정하기

🙌 Spring Security를 사용할 경우 WebMvcConfigurer만 설정해도 CORS 문제가 해결되지 않을 수 있습니다. 이럴 때는 SecurityFilterChain에서 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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.annotation.web.configurers.CorsConfigurer;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .cors(cors -> cors.configurationSource(request -> {
                var config = new org.springframework.web.cors.CorsConfiguration();
                config.addAllowedOrigin("http://example.com"); // 허용할 도메인
                config.addAllowedMethod("*"); // 모든 HTTP 메서드 허용
                config.addAllowedHeader("*"); // 모든 헤더 허용
                return config;
            }))
            .csrf(csrf -> csrf.disable()) // 필요시 CSRF 비활성화
            .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) // 모든 요청 허용 (설정에 맞게 수정)
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        return http.build();
    }
}