Framework/Security
Spring Security CORS 설정하기
호형
2021. 1. 7. 17:20
예전에 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.
끝!