SH380 Logo
2025-01-31

CORS 이해 및 설정

#CS

csgal-logo

1. 이론

2. 활용

  1. Controller 레벨
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class UserController {
    @GetMapping("/users")
    public List<User> getUsers() {
        return userService.findAll();
    }
}
  1. Global 설정 (모든 경로)
@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowCredentials(true)
                        .allowedHeaders("*");
            }
        };
    }
}

3. 심화

http.cors().and()
    .csrf().disable();

cors-graph

4. 면접 대비 핵심 포인트

5. 면접 연습


Q1. CORS가 필요한 이유?
A: 브라우저가 다른 출처 요청을 기본적으로 차단(SOP)하기 때문에, 서버가 허용 헤더를 반환해 클라이언트 요청을 허용해야 함.

Q2. Simple Request와 Preflight Request 차이?
A: GET/POST 등 단순 요청 → Simple Request. PUT/DELETE, 커스텀 헤더 포함 → 브라우저가 먼저 OPTIONS 요청 → Preflight Request.

Q3. allowCredentials(true) + "*" 가능한가?
A: 불가. 인증 정보 포함 요청 시 출처를 명시적으로 지정해야 함.

Q4. Spring Security에서 CORS 적용 시 주의점?
A: Security 필터가 CORS를 막으면 `@CrossOrigin` 또는 WebMvcConfigurer 설정이 적용되지 않음. `http.cors()`로 필터 순서 보장 필요.

Q5. Global CORS 설정과 Controller 레벨 설정 차이?
A: Controller 레벨: 특정 컨트롤러/메서드만 허용 Global 레벨: 모든 요청에 대해 공통 허용

6. 마무리

목록으로 돌아가기