Spring Boot

[Spring Boot] Spring Boot CORS 설정

그건모르겠고 2024. 6. 28. 00:01
728x90

CORS (Cross-Origin Resource Sharing)

개념

CORS는 Cross-Origin Resource Sharing의 약자로, 서로 다른 출처(도메인, 프로토콜, 포트) 간에 리소스를 공유할 수 있도록 하는 메커니즘입니다. 웹 애플리케이션에서 보안상의 이유로, 브라우저는 다른 출처의 리소스에 대한 요청을 제한합니다. CORS는 이러한 제한을 완화할 수 있도록 특정 조건하에 다른 출처의 리소스에 접근할 수 있는 방법을 정의합니다.

동작 원리

CORS는 HTTP 헤더를 사용하여 동작합니다. 서버는 특정 헤더를 포함하여 브라우저가 요청을 허용할 수 있도록 합니다.

  1. Preflight Request: 브라우저는 실제 요청을 보내기 전에 OPTIONS 메서드를 사용하여 "Preflight Request"를 보냅니다. 서버는 이 요청에 대한 응답으로 CORS 설정을 제공합니다.
  2. Simple Request: 브라우저는 Preflight Request 없이 바로 요청을 보냅니다. 이는 특정 조건을 만족하는 간단한 요청에 해당합니다.
  3. Actual Request: Preflight Request 후에 브라우저가 보내는 실제 요청입니다.

주요 HTTP 헤더

  • Access-Control-Allow-Origin: 요청을 허용할 출처를 지정합니다. *는 모든 출처를 허용합니다.
  • Access-Control-Allow-Methods: 요청을 허용할 HTTP 메서드를 지정합니다.
  • Access-Control-Allow-Headers: 요청을 허용할 HTTP 헤더를 지정합니다.
  • Access-Control-Allow-Credentials: 자격 증명(쿠키, 인증 헤더 등)을 포함한 요청을 허용할지를 지정합니다.
  • Access-Control-Max-Age: Preflight Request의 결과를 캐시할 시간을 지정합니다.

Spring Boot에서 CORS 설정

Spring Boot에서는 여러 가지 방법으로 CORS를 설정할 수 있습니다. 여기서는 전역 설정과 특정 컨트롤러에서 설정하는 방법을 설명합니다.

전역 설정

WebMvcConfigurer를 사용하여 전역적으로 CORS를 설정할 수 있습니다.

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("/**") // 모든 엔드포인트에 대해 CORS를 적용
                        .allowedOrigins("http://example.com") // 허용할 출처
                        .allowedMethods("GET", "POST", "PUT", "DELETE") // 허용할 메서드
                        .allowedHeaders("*") // 모든 헤더를 허용
                        .allowCredentials(true) // 자격 증명을 허용
                        .maxAge(3600); // Preflight 결과를 1시간 동안 캐시
            }
        };
    }
}

특정 컨트롤러에서 설정

특정 컨트롤러나 메서드에서 @CrossOrigin 애노테이션을 사용하여 CORS를 설정할 수 있습니다.

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

@RestController
@RequestMapping("/api")
public class MyController {

    @CrossOrigin(origins = "http://example.com", maxAge = 3600)
    @GetMapping("/data")
    public String getData() {
        return "Hello, CORS!";
    }
}

예제

다음은 간단한 Spring Boot 애플리케이션에서 CORS 설정을 적용하는 예제입니다.

프로젝트 설정

build.gradle 파일에 필요한 의존성을 추가합니다.

plugins {
    id 'org.springframework.boot' version '3.3.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

CORS 설정

WebConfig.java 파일에서 전역 CORS 설정을 구성합니다.

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("/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }
}

컨트롤러

MyController.java 파일에서 간단한 엔드포인트를 추가합니다.

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

@RestController
@RequestMapping("/api")
public class MyController {

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

프론트엔드 예제 (JavaScript)

다음은 CORS 설정이 적용된 Spring Boot 서버에 요청을 보내는 간단한 JavaScript 예제입니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CORS Example</title>
</head>
<body>
    <h1>CORS Example</h1>
    <button onclick="fetchData()">Fetch Data</button>
    <div id="result"></div>

    <script>
        async function fetchData() {
            try {
                const response = await fetch('http://localhost:8080/api/data', {
                    method: 'GET',
                    credentials: 'include' // 자격 증명 포함
                });
                const data = await response.text();
                document.getElementById('result').innerText = data;
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        }
    </script>
</body>
</html>

결론

CORS는 웹 애플리케이션 보안을 위해 중요한 역할을 합니다. Spring Boot에서 CORS를 설정하는 방법은 전역 설정과 특정 컨트롤러에서 설정하는 방법이 있습니다. 이를 통해 다른 출처에서의 요청을 적절하게 허용할 수 있습니다. 예제 코드를 통해 실제로 CORS가 어떻게 동작하는지 이해하고 설정할 수 있습니다.