CORS (Cross-Origin Resource Sharing)

2025. 6. 13. 13:57spring

반응형

CORS (Cross-Origin Resource Sharing)란?

  • CORS는 다른 도메인(Origin)에서 현재 서버의 리소스를 요청할 때 발생하는 보안 정책 문제를 제어하는 기술입니다.
  • 기본적으로 브라우저는 다른 출처(도메인, 포트, 프로토콜이 다른)에서 AJAX 요청하는 것을 막는데, 이를 허용할지 서버에서 설정하는 게 CORS입니다.

 

스프링에서 CORS 설정 방법

1) 글로벌 CORS 설정 (스프링 시큐리티 이전에)

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

@Configuration
public class WebConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")  // 모든 경로에 대해
                        .allowedOrigins("https://example.com")  // 허용할 출처 (모든 출처 허용은 "*" 가능)
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowCredentials(true)  // 쿠키, 인증정보 허용 여부
                        .maxAge(3600);
            }
        };
    }
}

2) 스프링 시큐리티에서 CORS 허용 추가하기

  • 시큐리티 필터가 MVC보다 먼저 실행되기 때문에, 시큐리티 설정에도 CORS 허용을 반드시 해줘야 합니다.
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()  // 스프링 시큐리티 CORS 활성화
        .and()
        .csrf().disable()
        .authorizeRequests()
        .anyRequest().authenticated();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

 

3) 컨트롤러 레벨에서 CORS 설정 (간단히 허용할 때)

@RestController
@CrossOrigin(origins = "https://example.com")
public class MyController {
    @GetMapping("/api/data")
    public String getData() {
        return "data";
    }
}
  • @CrossOrigin 애노테이션으로 특정 메서드 또는 클래스 단위로 CORS 정책을 설정할 수 있습니다.
반응형

'spring' 카테고리의 다른 글

스프링 필터  (1) 2025.06.13
스프링 인터셉터(Interceptor)  (0) 2025.06.13
CSRF (Cross-Site Request Forgery)  (1) 2025.06.13
스프링 JWT(JSON Web Token) 인증  (1) 2025.06.13
Spring Security  (0) 2025.06.13