[WIL] CORS

김대욱·2023년 2월 26일
1

CORS란 Cross-Origin Resource Sharing의 약자다.

https://www.example.com 도메인에 있는 웹페이지에서 API를 호출하려고 한다.
그 API는 https://www.api.com 도메인에서 호스팅되고 있을 때 리소스 공유가 불가능하다.
이때 CORS는 이 두 도메인 사이의 리소스 공유를 가능하게 해준다.

CORS를 허용하기 위해서는 서버 측에서 헤더를 설정해줘야 한다.
대표적인 헤더로는 Access-Control-Allow-Origin이 있다.

스프링 부트에서 CORS 설정하기

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();

        config.addAllowedOrigin("http://localhost:3000");
        config.addExposedHeader(JwtUtil.AUTHORIZATION_HEADER);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        config.validateAllowCredentials();

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return source;
    }

addAllowedOrigin() : 허용할 origin
addExposedHeader() : 노출할 헤더
addAllowedMethod() : 허용할 HTTP 메서드
addAllowedHeader() : 허용할 HTTP 헤더

setAllowCredentials(true) : 클라이언트에서 요청을 할 때, 인증 정보(cookies, authorization headers 등)를 함께 전송하는 것을 허용하는 설정

validateAllowCredentials() : allowCredentials가 true일 때, allowOrigin을 *으로 설정할 수 없도록 제약을 걸어주는 메서드

UrlBasedCorsConfigurationSource 객체를 생성하고, registerCorsConfiguration() 메서드를 통해 "/**" 경로에 대한 CORS 설정 정보를 등록해준다. 이 설정이 적용되면 모든 경로에서 CORS를 적용할 수 있게 된다.

0개의 댓글