spring boot cors에러 해결(Spring security,react)

한영진·2023년 1월 10일
0

cors 관련 문제해결
기본: WebMvcConfigurer을 implements받아 WebConfig에서 전역적으로 cors를 설정해줌

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {


        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOriginPatterns("*")
                    .allowedMethods("*")
                    .allowedHeaders("*")
                    .allowCredentials(true)
                    .maxAge(3600);



        }
}

괄호안에 "*" 은 wildcard로 어떤 것이든 허용한다는 뜻이다.

프로젝트 진행중 REACT와 통신을 하는 과정에서 CORS가 발생하여 문제를 해결 해보았다.
최종적으로 총 3가지 방법을 사용하여 문제를 해결하였는데 요약하여 정리해보면,

1.스프링부트 2.4.0버전부터 allowCredentials가 true일때 allowedOrigins에 ("*") 값을 추가 할 수 없게됨
->allowedOrigins를 allowedOriginPatterns로 변경 (WebConfig.class)


2.axios사용시 프론트 단에서도 allowCredentials를 true해줘야한다
아직 axios에대해 정확하게 알지는 못하지만 프론트에서 axios를 사용할때 allowCredential을 허용해줘야하는데 백에서뿐만아니라 프론트에서도 허용을 하니 cors에러가 사라졌다.

3.1,2번 문제해결후 회원가입은 정상적으로 작동했으나 로그인은 계속 cors문제가 발생하였다.
원인은 로그인 후 request응답 헤더에 Origin, Access-Control-Request-Method,Access-Control-Request-Headers이 빠져있었음
공식문서에 따르면 "springsecurity사용시 security 수준에서 cors설정해줘야한다"라고함
->spring security 사용시 추가 설정필요 (필터단에서 처리필요)

SpringSecurityConfig에서 httpSecurity.cors()를 통해 따로 설정을 해줌으로써 해결

참고)

1.https://cotak.tistory.com/248
2.https://velog.io/@uoayop/React-CORS
3.https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
https://emgc.tistory.com/131

profile
끊임없이

0개의 댓글