반응형

전자정부프레임워크를 사용한 REST API 개발에서 자주 발생하는 CORS(Cross-Origin Resource Sharing) 문제를 이해하고 해결하는 방법을 학습합니다. 특히, API를 클라이언트와 원활히 연동하기 위해 Spring Framework에서 제공하는 CORS 설정 방법을 살펴봅니다.


1. CORS란 무엇인가?

CORS(Cross-Origin Resource Sharing)는 웹 브라우저가 다른 도메인 간의 요청을 제한하는 보안 기능입니다.

  • 예시:
    • 클라이언트: http://localhost:3000
    • 서버: http://localhost:8080
    • 브라우저는 기본적으로 이러한 교차 출처 요청을 차단합니다.

CORS는 클라이언트와 서버 간 데이터 공유를 허용하기 위해 HTTP 헤더를 통해 특정 도메인을 허용하도록 설정할 수 있습니다.


2. CORS 이슈 예제

클라이언트에서 REST API 요청 시 발생할 수 있는 오류:

Access to XMLHttpRequest at 'http://localhost:8080/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

3. 해결 방법

3-1. Spring에서의 CORS 설정 방법

  1. Global CORS 설정: 모든 요청에 대해 전역적으로 적용합니다.
  2. 컨트롤러 레벨에서 CORS 설정: 특정 엔드포인트에만 적용합니다.

3-2. Global 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 WebConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")  // CORS를 적용할 경로
                        .allowedOrigins("http://localhost:3000")  // 허용할 클라이언트 도메인
                        .allowedMethods("GET", "POST", "PUT", "DELETE")  // 허용할 HTTP 메서드
                        .allowedHeaders("*")  // 모든 헤더 허용
                        .allowCredentials(true);  // 인증 정보 허용
            }
        };
    }
}

3-3. 컨트롤러 레벨에서 CORS 설정

컨트롤러 메서드에만 CORS를 설정하려면 @CrossOrigin 어노테이션을 사용합니다.

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/api/data")
    public String getData() {
        return "CORS 설정이 완료된 데이터";
    }
}

3-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.csrf().disable()
            .cors()  // CORS 설정 활성화
            .and()
            .authorizeRequests()
            .antMatchers("/api/**").permitAll();

        return http.build();
    }
}

4. 테스트 방법

  1. API 호출 전:
    • 클라이언트에서 CORS 정책 위반으로 인해 요청이 실패합니다.
  2. API 호출 후:
    • 설정이 완료되면 클라이언트에서 서버로의 요청이 정상적으로 처리됩니다.

HTTP 요청 예제 (JavaScript):

fetch('http://localhost:8080/api/data', {
    method: 'GET',
    credentials: 'include', // 쿠키 인증을 사용하는 경우
})
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

5. 주요 참고 사항

  • 개발 환경에서만 허용 도메인 설정:
    운영 환경에서는 동적으로 CORS 정책을 관리하거나, 정적 파일의 배포 도메인을 정확히 지정합니다.
  • 보안 고려:
    허용된 도메인을 제한적으로 설정하고, 불필요한 요청 메서드는 허용하지 않는 것이 중요합니다.

6. 마무리

이번 학습에서는 REST API에서 자주 발생하는 CORS 문제를 이해하고, 이를 해결하기 위한 Spring 설정 방법을 배웠습니다. 이러한 설정은 클라이언트와 서버 간의 원활한 통신을 보장하며, 보안 및 효율성을 높이는 데 필수적입니다.
다음에서는 전자정부프레임워크와 외부 API 연동을 다룹니다.

반응형

+ Recent posts