개발/spring-security

SpringSecurity - CORS 허용

나태쿤 2024. 5. 12. 22:10
728x90

기본적으로 현재 A 라는 사이트에서 B 사이트를 요청하면 브라우저 정책에 따라서 막힌다

 

 

서버사이드 랜더링에서는 문제를 못접하겠지만  ( ex. JSP, 타임리프 )

 

프론트 / 백엔드로 구성된 애플리케이션에서는 자주 나오는 상황이다

ex. 리액트 , 스프링

 

그럴때 API 서버인 백엔드 애플리케이션에서 프론트를 받아줄 수 있게 허용해야한다

 

 

여기서 요청을 2개로 나눌 수 있는데

 

예비요청본요청 이다

 

1.  SimpleRequest  : 본 요청으로 바로 요청 

 

- HTTP 메서드 :  GET, POST, HEAD 가능

- 커스텀 헤더 불가

- 컨텐츠 타입은 application/x-www-form-urlencoded, multipart/form-data, text/plain 만 가능 하고

   application/json, text/xml 은  불가능하다

 

따라서 컨텐츠 타입에 따라서 요청이 바뀔 수 있다

 

 

 

2. Preflight  : 예비요청 후 본요청 

프리플라이트는 요청을 해도 안전한지 미리 사전에 서버에 요청을 보내는 것이다 (넠넠넠 노크)

 

- HTTP 메서드 : OPTIONS

 

응답 헤더를 보면 Access 관련 Header가 여러개 추가된걸 볼 수 있다

 

 

 

설정은 Spring MVC로도 가능하지만 Spring Security 로 사용할 경우 다음과 같이 하면된다

 

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
@EnableWebSecurity
@Configuration
public class SecurityConfig {
 
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
 
        http.authorizeHttpRequests(auth -> auth
                        .anyRequest().permitAll())
            .cors(cors -> cors
                    .configurationSource(corsConfigurationSource()));
        return http.build();
    }
 
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
 
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://localhost:8080");    // Request 의 Origin 과 일치하는 경우에만 리소스 허용, 와일드 카드 * 사용
        configuration.addAllowedMethod("*");                        // 허용되는 HTTP 메서드 지정
        configuration.addAllowedHeader("*");                        // 허용되는 HTTP 요청 헤더 지정
        configuration.setAllowCredentials(true);                    // 클라이언트의 인증 관련된 쿠키 포함 가능
        configuration.setMaxAge(1L);                                // preflight 요청의 결과를 캐시할 수 있는 초 단위
 
        // URL 베이스로 CORS 설정
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
 
        // 모든 컨트롤러에 Cors 환경설정 적용
        source.registerCorsConfiguration("/**", configuration);
 
        return source;
 
    }
 
 
}
cs
728x90