Spring Security Cors Mapping Error
- Error
- 2021년 5월 2일
CORS 란?
Cross-Stie HTTP Requests의 약자로 한 도메인이 다른 도메인의 자원을 사용하는 것을 의미하는데, chrome cors 기본정책이 strict-origin-when-cross-origin으로 Same Origin에 대해서만 자원을 사용하도록 제한되어 있다. 여기서 Same-Origin이란 호스트명, 프로토콜, 포트가 같은 도메인을 말한다.
Front 서버와 Back서버를 나눠 개발을 진행하다 보면 두 주소(포트)가 달라 cors에러가 발생한다. 그래서 서버단에서 특정 origin을 허용할 수 있게 cors설정을 추가로 해주어야 한다.
1. Config
SpringBoot에서 Cors 설정을 위해서는 filter, annotation, config를 이용하는 방법이 존재하는데 그중 하나인 config 설정을 아래와 같이 적용해 줄 수 있다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //패턴
.allowedOrigins("http://localhost:8080","http://localhost:8081") //특정 URL 설정
//.allowedOrigins("*") //All Allow
// .allowedOriginPatterns("*") //All Allow
// .allowedOriginPatterns("http://localhost:*") //Pattern 적용 가능
.allowedHeaders("header1","header2") //header
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") //method
.allowCredentials(true); //false 면 cookie 설정 불가능
}
}
WebMvcConfigurer 인터페이스를 구현한 Config 클래스를 빈으로 등록함으로써 CORS 정책을 등록해줄 수 있는데, 위와 같은 메서드드들로 특정 URL만 cors를 허용해줄 수 있으며 “*“와 같이 작성하면 모든 URL에 대해 허용해줄 수 있다.
allowCredentials 를 true로 설정해주었다면, 보안 정책상 allowedOrigins(”*")는 불가능하다. 그럼에도 모든 요청에 대한 허용을 하고 싶다면 allowedOriginPatterns(”*")를 이용하면 된다.
2. Spring Security Config
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().disable()
.cors() //Cors 옵션 활성화
//...다른 설정들 생략
;
}
//Cors 설정
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*");
// configuration.addAllOriginPatterns("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
적용방식은 1번과 거의 비슷한데, CorsConfigurationSource 빈을 위와 같이 설정하여 등록해주면 된다.
3. 에러
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
CORS 설정하다보면 위와 같은 에러를 만날 수도 있는데, 해결방법은 간단하다. AllOrigin("*") 과 allowCrededentials(true) 를 동시에 사용할 수 없어서 나는 에러로 AllOriginPatterns("*") 를 이용하거나 특정 URL만 허용해주면 된다.