본문 바로가기
Spring

[오류해결] Spring security CORS 문제

by HanYaung 2025. 3. 25.

CORS란?

  • CORS(Cross-Origin Resource Sharing) 오류는 웹 페이지가 다른 도메인의 리소스에 접근하려고 할 때 브라우저의 보안 정책에 의해 발생하는 오류이다
  • 프론트엔드의 IP가 123.456.789:3000 이고 백엔드 IP가 123.456.789:8080로 rest api 로 데이터를 전달시 브라우저에서 123.456.789:3000와 다른 123.456.789:8080의 도메인 접근을 막아서 생긴 오류이다
  • 프로토콜(예: http, https), 호스트(도메인 이름), 포트가 모두 같아야 CORS가 발생 안한다

 

해결방법

도메인을 허용해줌

    // securityconfig
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        // 허용할 도메인 설정
        config.setAllowedOrigins(Arrays.asList(
                "https://snowper.shop",
                "https://www.snowper.shop",
                "http://localhost:5173"
        ));

        // 허용할 HTTP 메서드
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS","PATCH"));

        // 허용할 헤더
        config.setAllowedHeaders(Arrays.asList("*"));

 

'Spring' 카테고리의 다른 글

Spring MSA 멀티 모듈 레포 구성 방법  (0) 2025.03.27
[오류해결] jpa N+1 문제  (0) 2025.03.26
Spring Cloud Eureka MSA 사용법  (0) 2025.03.06