포스트

VITE - Spring Boot CORS 설정

CORS 설정 웹 개발에서의 CORS 설정

CORS란?

CORS(Cross-Origin Resource Sharing)는 웹 애플리케이션이 하나의 출처에서 실행되는 리소스가 다른 출처의 리소스에 접근할 수 있도록 허용하는 보안 기능이다. 웹 브라우저는 보안상의 이유로 기본적으로 다른 출처(도메인, 프로토콜, 포트)의 리소스에 접근하는 것을 제한한다. 이러한 제약을 동일 출처 정책(Same-Origin Policy)이라고 하며, 이를 우회하기 위해 CORS가 도입되었다.

CORS 설정하는 이유

웹 애플리케이션 개발에서 CORS를 설정하는 주된 이유는 다음과 같다.

  1. 다른 출처의 API에 접근하기 위해:
    • 웹 애플리케이션은 자주 다른 출처의 API와 상호작용한다. 프론트엔드에서 서버 API를 호출할 때 서버가 다른 도메인에 있을 경우, 브라우저는 보안상의 이유로 기본적으로 이러한 요청을 차단한다. CORS 설정을 통해 이러한 요청을 허용할 수 있다.
  2. 보안 유지:
    • CORS는 보안 정책을 유지하면서도 특정 출처에서의 요청을 허용할 수 있도록 한다. 이를 통해 민감한 데이터에 대한 무단 접근을 방지하고, 신뢰할 수 있는 출처에서만 리소스 접근을 허용할 수 있다.
  3. 개발 환경에서의 편의성:
    • 개발 중에는 프론트엔드와 백엔드 서버가 종종 다른 도메인에서 실행된다. 예를 들어, 본인 프로젝트의 로컬 환경에서 프론트엔드는 http://localhost:5173에서, 백엔드는 http://localhost:8088에서 실행하였다. 이 경우, CORS 설정을 통해 개발 중에 발생하는 도메인 간의 요청 문제를 해결할 수 있다. 이를 통해 프론트엔드와 백엔드를 원활하게 통합하고 테스트할 수 있다.

Vite에서 CORS 설정

Vite를 사용할 때 CORS 문제를 해결하기 위해서는 vite.config.js 파일에서 프록시 설정을 해줄 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
    plugins: [react()],
    server: {
        proxy: {
            "/api": {
                target: "http://localhost:8088",
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ""),
            },
        },
    },
});

SpringBoot에서 CORS 설정

메인 애플리케이션 클래스에서 CORS 설정을 추가할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import com.petstagram.config.AuditorAwareImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@EnableJpaRepositories
@EnableJpaAuditing
@EnableScheduling
@SpringBootApplication
public class PetstagramApplication {

    @Bean
    public AuditorAware<String> auditorProvide() {
        return new AuditorAwareImpl();
    }

    public static void main(String[] args) {
        SpringApplication.run(PetstagramApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**") 
                        .allowedMethods("*") 
                        .allowedOrigins("http://localhost:5173");
            }
        };
    }
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.