Java/Spring

[Spirng] CORS 처리하는 법

뉴벡엔드 2024. 4. 30. 11:32

CORS(Cross-Origin Resource Sharing)

웹 페이지의 리소스를 다른 도메인에서 요청할 수 없게 제한하기 위한 웹 브라우저에 구현된 보안 기능입니다.

악의적인 웹사이트가 허가 없이 다른 사이트와 상호 작용하는 것을 방지할도록 설게되어 사용자 데이터가 허가되지 않은 당사자에게 노출되는 것을 방지할 수 있습니다.

 


처리방법

 

1. 글로벌 CORS 구성

모든 컨트롤러에 전역적으로 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 implements WebMvcConfigurer {
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // All paths
            .allowedOrigins("http://example.com") // Origins allowed to access
            .allowedMethods("GET", "POST", "PUT", "DELETE") // HTTP methods allowed
            .allowedHeaders("*") // Headers allowed in the request
            .allowCredentials(true) // Credentials allowed
            .maxAge(3600); // Max age of the CORS request
    }
}

 

 

2. 컨트롤러 수준 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
@CrossOrigin(origins = "http://example.com") // 이 컨트롤러의 모든 메서드에 CORS를 적용 
public class ExampleController {

    @GetMapping("/data")
    public String getData() {
        return "Data from server";
    }
}

 

 

컨트롤러의 모든 메서드가 아닌 컨트롤러의 특정 메서드에 선택적으로 CORS 적용

 

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

@RestController
public class ExampleController {

    @CrossOrigin(origins = "http://example.com")
    @GetMapping("/publicData")
    public String getPublicData() {
        return "Public data accessible from example.com";
    }

    @CrossOrigin(origins = "http://example.org", methods = { "POST" }, allowedHeaders = { "X-Custom-Header" })
    @PostMapping("/updateData")
    public String updateData() {
        return "Data update endpoint, accessible from example.org with custom headers";
    }

    // CORS를 허용하지 않습니다.
    @GetMapping("/privateData")
    public String getPrivateData() {
        return "This data is private and not exposed to CORS";
    }
}

 

 

반응형