Spring Security Cors Mapping Error

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만 허용해주면 된다.

Related Posts

[Disjoint Set] Union Find 알고리즘

[Disjoint Set] Union Find 알고리즘

1. Disjoint Set 번역하면 서로소 집합으로 서로 중복 되지 않는 부분 집합들로 이루어진 집합(set)으로 교집합이 존재 하지 않는 부분집합들로 이루어진 집합이다. 2. Union-Find Union : 두개의 집합을 하나의 집합으로 합치는 것. Find : 어떤 원소가 주어졌을 때 이 원소가 속한 집합을 반환하는(찾는) 것. 집합들을 tree구조로 나타내어 해당원소가 어떤 집합에 속하는지 판단...

Read More
Heap

Heap

Tree중 하나로 최대,최솟값을 찾아내는 연산을 빠르게 하기 위한 완전 이진 트리이다. (Complete Binary Tree ) 우선 순위를 무엇에 두냐에 따라 순서가 달라지기 때문에 자료가 들어온 시간을 우선순위로 놓는다고 하면 일반적인 큐도 우선순위 큐가 될 수 있다. 1. 최대 힙(Max Heap) 부모 노드의 key값이 자식 노드의 key값보다 크거나 같은 완전 이진 트리 c++을 이용한...

Read More
spring boot Graphql CustomContext 생성하기

spring boot Graphql CustomContext 생성하기

GraphQL의 요청을 핸들링하는 GraphQLServletContextBuilder를 implements하여 grpahQL요청에 대해 커스텀Context를 반환하도록 만들 수 있다. 예를들어 요청의 헤더에 접근하여 Context에 특정 헤더값을 저장하는 식으로의 custom이 가능하다. 이번 예시에서는 헤더에 a...

Read More