Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NDD-97]: CORS를 위한 모듈 추가(1h/1h) #26

Merged
merged 3 commits into from
Nov 9, 2023
Merged

Conversation

JangAJang
Copy link
Collaborator

@JangAJang JangAJang commented Nov 9, 2023

NDD-97 Powered by Pull Request Badge

Why

스크린샷 2023-11-09 19 17 23
스크린샷 2023-11-09 19 17 35
BE 인스턴스와 DB 인스턴스를 연 후 DB 인스턴스에서 BE 인스턴스가 사용가능한 계정을 만들었다.
이를 BE에서 받고 서버를 정상적으로 동작시켰지만, BE 인스턴스 기준으로, 클라이언트가 호스트에서의 응답을 받지 못하고 있다.
이를 CORS가 설정되지 않은 것이 원인이라고 판단하고 CORS를 처리해야겠다고 생각했다.

How

CORS에 대해서, 고려해야 할 사항이 있었다.

  1. 개발중엔 모든 사용자가 CORS를 통과해야 한다.
  2. 배포후엔 FE 호스트만이 BE 인스턴스에 클라이언트로 접근할 수 있어야 한다.
  3. nestjs의 CORS는 origin, headers를 문자열의 배열로 받는다.
    이를 해결할 방안을 생각해야했다.

Cors의 Option을 CORS_CONFIG 객체로 초기화시키자.

CorsOptions라는 인터페이스(타입)이 존재한다. 해당 타입을 받을 수 있도록 코드를 만들어보았다.

export const CORS_CONFIG: CorsOptions = {
    origin: ['localhost:8080', '통과시켜줄 origin'],
    credentials: true,
    exposedHeaders:['Authorization', '통과시켜줄 헤더들'],
}

이런 구조로 이해를 했다.
이후, 헤더와 origin을 문자열의 배열로 담아줄 다른 모듈이 필요했다.
이를 .env로 처리하자니 문제가 있었다.

DATABASE_PORT=3306
DATABASE=gomterview
SALT=10

이런 식으로 존재하는 숫자들도, process.env로 읽어오면 문자열로 처리가 되고 있었다.
이를 위해 Number(process.env.DATABASE_PORT)처럼 문자열을 파싱해주는 로직이 필요했다.
env는 문자열을 배열을 담기 위해서, ORIGINS=a,b,c,d라고 존재할 때, 이를 process.env.ORIGINS.split(",")의 로직을 반복적으로 넣어주어야 한다.

이렇게 해당 데이터를 받아올 때 마다 파싱하기보단, 차라리 ts파일을 .gitignore에 추가하고, 이를 import해서 사용하는 방식이 나을 것 같다는 생각이 들었다.

Result

import {CorsOptions} from "@nestjs/common/interfaces/external/cors-options.interface";
import {CORS_HEADERS, CORS_ORIGIN} from "./cors.secure"; // cors.secure 모듈은 gitignore에 등록했다.

export const CORS_CONFIG: CorsOptions = {
    origin: CORS_ORIGIN,
    credentials: true,
    exposedHeaders: CORS_HEADERS,
}
// main.ts
...
app.enableCors(CORS_CONFIG);
...

해당 코드들을 통해 Postman으로 검증하고, 헤더에 CORS설정이 되어있는지 확인했다.
스크린샷 2023-11-09 20 26 13
에서 CORS관련 설정이 되어있는 것을 확인할 수 있다.

Prize

요청을 받을 때, 8080포트에 관해서는 원하는 origin의 요청만을 받을 수 있게 되었다.
이를 통해 백엔드 서버에서 다른 ip의 요청을 막을 수 있다.

Link

https://milk717.atlassian.net/browse/NDD-97

@JangAJang JangAJang changed the title [NDD-97]: CORS를 위한 모듈 추가 [NDD-97]: CORS를 위한 모듈 추가(1h/1h) Nov 9, 2023
@adultlee
Copy link
Collaborator

adultlee commented Nov 9, 2023

잘봤습니다!! 꼼꼼하게 작성하신게 인상깊어요!! 어프로브 누르고 갑니다 😊

Copy link
Collaborator

@quiet-honey quiet-honey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

골치 아픈 CORS 해결 고생하셨습니다!!

@JangAJang JangAJang merged commit 35cb8e6 into dev Nov 9, 2023
@delete-merged-branch delete-merged-branch bot deleted the feature/NDD-97 branch November 9, 2023 12:58
@adultlee adultlee added the BE 백엔드 코드 변경사항 label Nov 9, 2023
Yoon-Hae-Min pushed a commit that referenced this pull request Nov 11, 2023
* docs: gitignore에서 사용해야하는 CORS의 문자열 배열들을 깃에 올리지 않도록 추가

* feat: cors의 설정을 처리하는 json 추가

* feat: app이 CORS_CONFIG를 받아서 CORS 필터에 대한 조건을 명시하도록 기능 구현
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BE 백엔드 코드 변경사항
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants