CORS (Cross Origin Resource Sharing)

Created
2023/11/27 01:51
담당자

Problem

CORS (Cross Origin Resource Sharing)
웹 브라우저에서 다른 출처(Origin)로부터 리소스를 요청할 때 발생하는 보안 문제를 해결하기 위한 표준 기술입니다.
CORS는 HTTP 헤더를 사용하여 브라우저와 서버 간에 통신하는 동안 발생할 수 있는 문제를 해결합니다. 서버는 응답 헤더에 Access-Control-Allow-Origin 헤더를 포함하여 어떤 출처의 요청을 허용할지 지정합니다. 브라우저는 이 헤더를 확인하여 요청이 허용되었는지 판단하고, 허용된 경우에만 리소스에 접근합니다.
CORS를 사용하여 보안성을 유지하면서도 다른 출처의 리소스를 자유롭게 사용할 수 있으므로, 모던 웹 애플리케이션에서는 필수적인 기술 중 하나입니다.
백엔드 서버와 프론트 엔드 서버 연동 작업 중 header에 액세스 토큰을 담아 보내는 API 요청 시 CORS 에러

Try to solve

BE
1 ) WebMvcConfigurer 에서 프론트에서 접근하는 urlhttp://localhost:5173/ allowedOrigins로 설정해두었습니다. 하기는 설정해 둔 코드입니다.
public void addCorsMappings(CorsRegistry registry) { WebMvcConfigurer.super.addCorsMappings(registry); registry.addMapping("/**") .allowedHeaders("*") .allowedOrigins("https://stately-yeot-007fa8.netlify.app") .allowedOrigins("https://mlf.vercel.app") .allowedOrigins("http://localhost:8080") .allowedOrigins("http://localhost:3000") .allowedOrigins("http://localhost:5173") .allowedMethods("GET", "POST", "DELETE", "PUT", "HEAD", "OPTIONS") .exposedHeaders("Authorization") .allowCredentials(true); }
Java
복사
2) 1의 조치를 했음에도 프론트에서 여전히 똑같은 문제가 발생하여서,
HttpSecurity 설정을 하기와 같이 변경하여습니다.
http.cors().disable() httpBasic().disable() .csrf().disable() .headers().frameOptions().disable();
Plain Text
복사
FE
서버 측에서 Config 설정 이후에도 해결이 안 되는 경우, 클라이언트 측에서 프록시 서버를 설정하여 해결할 수 있다. 프록시 서버 우회는 개발 환경에서만 가능하므로 주의한다.
Proxy는 API로 네트워크 요청 / 응답을 주고 받는 클라이언트와 서버 사이를 중개하는 중간자 역할이다. Proxy 설정을 한다면 요청을 날릴 때 Origin을 바꿔서 서버에 날릴 수 있다.
vite.config.ts
server: { proxy: { "/api": { target: "http://20.214.139.103:8080", changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ""), secure: false, ws: true, }, }, },
TypeScript
복사
customAxios.ts
const customAxios: AxiosInstance = axios.create({ withCredentials: true, baseURL: "/api", });
TypeScript
복사
해결 완료
localhost → 127.0.0.1로 변경하고 setAllowedHeaders , setExposedHeaders 를 모든 요청에 대해 오픈하였더니 해결되었음
@Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfigurationconfig= new CorsConfiguration(); config.setAllowCredentials(true); config.setAllowedOrigins(Arrays.asList( "http://127.0.0.1:8080", "http://127.0.0.1:5173", "https://mlf.vercel.app", "https://stately-yeot-007fa8.netlify.app" )); config.setAllowedMethods(Arrays.asList( HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.DELETE.name(), HttpMethod.PUT.name(), HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name() )); config.setAllowedHeaders(Arrays.asList("*")); config.setExposedHeaders(Arrays.asList("*")); UrlBasedCorsConfigurationSourcesource= new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**",config); returnsource; }
JavaScript
복사