포스트

Spring Boot - CORS 설정

CORS 란?

Cross Origin Resource Sharing
교차 출처 리소스 공유


웹페이지 상의 제한된 리소스를 최초 자원이 서비스 된 도메인 밖의 다른 도메인으로 부터 요청할 수 있게 하는 것. - 위키백과



Spring Boot Security 설정

Spring Boot 3.2.0 기준


SecurityConfig.java

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 org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
public class SecurityConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(List.of(
                "http://127.0.0.1:8080",
                "http://localhost:8080",
                "http://zhyun.kim:8080"));
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);

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

    
    @Bean  
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {  
    
        // ...
      
        http.cors(withDefaults());  
      
        // ...
      
        return http.build();  
    }

}

CorsConfiguration

  • config.setAllowedOrigins("url")
    • 접근을 허용할 도메인명 기입
  • config.setAllowCredentials(true)
    • 쿠키, 인증 헤더, TLS 클라이언트 인증서 등의 자격 증명을 허용할 지 설정
    • 기본값은 false 이다.
    • 이 값을 true로 설정하지 않으면 자격증명이 포함된 요청은 접근 거부된다.
    • 이 값을 true로 설정할 경우 setAllowedOrigins() 값으로 와일드 카드(*)는 사용할 수 없고
      허용할 도메인을 모두 기입해야 한다.
  • config.addAllowedMethod()
    • 허용할 http method 기입
  • config.addAllowedHeader()
    • 허용할 요청 헤더 기입
      • 기본적으로 cors 요청은 일부 표준 헤더 (Content-Type, Accept, Origin)만 허용한다.
      • Authorization, 사용자 정의 헤더 등 비표준 헤더를 사용하는 경우 설정을 추가해주어야 한다.

UrlBasedCorsConfigurationSource

  • cors 설정을 URL 패턴에 적용하는 클래스
  • 이 클래스를 사용하여 다양한 URL 패턴에 서로 다른 CORS 설정을 적용할 수 있다.
  • source.registerCorsConfiguration("/**", config)
    • cors 설정을 특정 URL 패턴에 적용
    • /** 패턴은 모든 URL 경로에 적용하는것을 의미한다.




참고한 사이트

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.