서버

프론트(nginx) + 백엔드(tomcat, springboot) cors 해결과정

탐훈 2023. 9. 26. 00:59
728x90

초반에 nginx에 cors가 걸리는 줄 알고 

nginx(웹서버)에만 conf 파일 엄청 수정했다.

 

생각해보니 cors에러는 백단과 났던 것이다.. 

 

머리가 나쁘면 몸이 고생한다고.. 

nginx에다가 cors수정하면서 안된다고 3시간 정도 날린 듯 하다..

 


현재 프로젝트 아키텍처가 다음과 같다.

nginx(웹서버) + tomcat(WAS) 

 

예를 들어

nginx에서 로그인 시 was로 api를 요청한다.

 

nginx 주소와 다른 

주소에 리소스를 받아오는 게 감지되어

브라우저에서 cors에러를 내버린다. 

 

그래서 was의 spring boot를 다음과 같이 설정했다.

package com.oliveyoung.web.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsController implements WebMvcConfigurer {

	  @Override
	  public void addCorsMappings(CorsRegistry registry) {
	    registry.addMapping("/**")
	        .allowedOrigins("http://49.247.40.173");
	  }
}

 

모자이크는 

넘어오는 url이다.

ex) http://ip주소 

 


nginx에서 

was로 api를 쏠 때

cors가 걸리는지 확인하기 위해 좋은 방법이 있다.

 

바로 curl을 사용하는 것이다.

다음과 같은 순서로 테스트하면 된다.

 

nginx ssh 접속 -> curl -v http://백단주소 -> 응답에 access-control 영역 확인하기

 


[1. nginx ssh 접속 ]

 

[2. curl -v http://백단주소]

요청을 하게되면 

vary 부분에 origin이라고 적혀있다.

 

orgin은 조건부로 허가된다는건데 

모든 요청을 허가된 주소는 어떻게 나오는지 보자

 

Access-Control-Allow-Origin: * 로 표기된다.

모두 허가된다는 뜻이다. 

 

nginx에서 

모두 허가시키는 conf 설정은 다음과 같다.

 

location / {
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        #
        # Om nom nom cookies
        #
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
 
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
 
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
}