티스토리 뷰

예전에 CORS(Cross-Origin Resource Sharing)filter를 사용해서 설정하는것에 대해 포스팅을 한적이 있다. Spring Security를 사용하면 이렇게 별도의 filter를 만들지 않고 간단하게 CORS 설정을 할 수 있다. 

 

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// http formLogin, headers .. 설정
http.cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
... 생략...
}

Spring Security 설정파일인 SecurityConfig.java 파일이다. configure 메소드의 맨 마지막줄을 보면 CORS는 HttpSecurity의 cors() 메소드로 설정을 할 수 있다. 그리고 CorsConfigurationSource를 통해 CORS의 속성을 정의해 줄 수 있다. 

 

위에서 사용한 CorsConfiguration의 메소드는 다음과 같다.

 

  • setAllowedOrigins : A list of origins for which cross-origin requests are allowed.
  • setAllowedMethods : Set the HTTP methods to allow
  • setAllowedHeaders : Set the list of headers that a pre-flight request can list as allowed for use during an actual request.
  • setAllowedCredentials : Whether user credentials are supported.

 

끝!

 

최근에 올라온 글
최근에 달린 댓글
«   2025/04   »
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