권한 설정

Npm 의 디렉토리 위치 찾기

$ npm config get prefix

 

출력이 "/usr/local"  이면 아래 명령어를 실행하여 권한을 설정

$ sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

 

nest 설치

 

$ npm i -g @nestjs/cli # Nest 프로젝트를 간편하게 생성할 수 있게 도와주는 라이브러리
$ nest new my-web-server # my-web-server(프로젝트 이름)이라는 이름으로 Nest 프로젝트를 생성

 

 

참고자료

https://stackoverflow.com/questions/47252451/permission-denied-when-installing-npm-modules-in-osx

 

Permission denied when installing npm modules in OSX

I'm trying to install node-g.raphael, and I'm getting the following error: Bender-03:htdocs alfred$ sudo npm install node-g.raphael --save Password: > contextify@0.1.15 install /Users/alfred/

stackoverflow.com

https://docs.nestjs.com/first-steps

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

Node.js + express.js 사용

  • 설치 
npm i cors
  • 코드 예시

>  모든 요청 허용

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This allow all CORS request'})
})

// 나머지 서버 코드...

 

>  특정 도메인 허용

const express = require('express');
const cors = require('cors');
const app = express();

const corsOptions = {
    origin: 'http://example.com', // 특정 도메인 허용, 리스트로 작성 가능
    methods: 'GET,POST,PUT,DELETE', // 허용하는 HTTP 메소드
    credentials: true // 쿠키/인증 정보 허용
}

app.use(cors(corsOptions));

app.get('/products/:id', (req, res) =>{
	// 나머지 코드...
})

// 나머지 코드...

 

아래 참고자료 링크에서 더 많은 예제 및 옵션 참고 가능

참고자료

https://www.npmjs.com/package/cors

*Origin: scheme(protocol), hostname(domain), port of URL

 

HTTP-header 기반의 보안 메커니즘

즉, web brower에서 실행 되는 보안 조치

 

탄생배경

  • 도메인간의 요청이 오고가면서 보안의 위험이 발생
  • SOP(the same-origin policy)의 한계 발생
    • SOP:  한 도메인의 문서나 스크립트가 어떻게 다른 도메인과 상호작용을 할건지에 대한 보안 메커니즘
    • 한계점
      • 다른 도메인들에 있는 API들간의 데이터 공유시 보안 문제
      • 웹 app 에서 다루는 다양한 소스로 부터 얻은 데이터 처리
      • 최근 웹 어플리케이션에서 발생 하는 다양한 리소스및 서비스간 의  cross-origin interaction을 다루지 못함
        • 다른 도메인에서 리소스 로드
        • 외부서비스에 API call 생성 ( 한 app 에서 다른 서버에 있는 API에 요청을 하는 행위)

목적

  • SOP 를 기반으로 유연하고 안전하게 cross-origin requests 를 하기 위함
  • 유저의 데이터 보호
  • 악의적인 웹페이지가 다른 도메인의 민감한 정보에 대한 접근을 방지

 

동작방식

  1. 웹 페이지 A가 특정 서버에 데이터를 요청
  2. 원하는 것이 무엇인지에 대한 정보가 있는 `Origin`을 헤더에 담아서 요청 전송
  3. 해당 서버는 CORS 정책에 따라 이 요청을 허락할지 거절할지 결정
  4. 요청을 허락하게 되면 CROS 는 `Access-Control-Allow-Origin` 라는 헤더에 허락된 origin 정보를 담아서 응답
    • 이 헤더에는 허락된 origin을 담거나, 모든 origin을 허용하는 와일드 카드인 `*` 를 사용할 수 있다. 

 

참고자료

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

https://www.npmjs.com/package/cors

https://chat.openai.com/c/67d26a77-236d-4937-968a-412b96379988

ChatGPT 답변 + 내용 수정

더보기

Certainly! CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented in web browsers to manage how web applications running at one origin (domain) can request resources from another origin.

Here's a breakdown of its key aspects:

  1. Same-Origin Policy: By default, web browsers enforce a security measure called the Same-Origin Policy (SOP). This policy restricts web pages from making requests to a different domain than the one that served the web page. Its primary purpose is to protect user data and prevent malicious scripts on one page from obtaining access to sensitive data on another.
  2. The Need for CORS: Sometimes, legitimate web applications need to make cross-origin requests. For example, a web application hosted on example.com might need to request resources from api.example.com or a third-party API hosted on a different domain. CORS provides a way to allow these cross-origin requests safely.
  3. How CORS Works: CORS works through HTTP headers.
    • When a web application makes a cross-origin request, the browser sends an HTTP request to the target server with an `Origin` header, indicating the origin of the request.
    • The server can then decide whether to allow or deny the request based on its CORS policy. If the server allows the request, it responds with specific CORS headers, like `Access-Control-Allow-Origin`, indicating which origins are permitted.
    • This header lists the allowed origns or a wildcard to indicagte that any origins is allowed.
  4. Simple and Preflight Requests: There are two types of CORS requests - Simple and Preflight. Simple requests are basic requests like GET or POST with certain safe headers, and they are sent directly with CORS headers. Preflight requests are more complex and use methods like PUT or DELETE, or include custom headers. These are first sent with an OPTIONS request to check if the actual request is safe to send.
  5. Security and Limitations: While CORS enables cross-origin requests, it also includes mechanisms to ensure security. It doesn't allow arbitrary sharing of user credentials like cookies or HTTP authentication unless explicitly permitted by the server. Also, CORS policies are set server-side, meaning the server has full control over who can access its resources.

In summary, CORS is an essential part of modern web security. It enables controlled cross-origin requests, balancing the need for functionality with the need to protect users' data and privacy.

 

Simple Example

 

Imagine you have two websites:

  1. Website A: https://website-a.com, which is a frontend application.
  2. Website B: https://api.website-b.com, which provides an API that Website A wants to use.

Scenario Without CORS

  • A user visits https://website-a.com.
  • Website A tries to fetch user data from https://api.website-b.com/data.
  • The browser's Same-Origin Policy blocks this request because it's a cross-origin request (the origin of the frontend app is website-a.com, and it's trying to access data from api.website-b.com).

Implementing CORS

To allow this cross-origin request, Website B (the API server) needs to include a specific header in its response.

Steps in the CORS Process

  1. The Browser Sends a Request: When the frontend app at Website A makes a request to Website B, the browser automatically adds an Origin header to the request, indicating that the request is coming from https://website-a.com.
  2. Server Checks the Origin: Website B's server receives the request and checks the Origin header.
  3. Server Responds with CORS Headers: If Website B's server is configured to allow requests from https://website-a.com, it responds with a header like Access-Control-Allow-Origin: https://website-a.com. This header tells the browser that the cross-origin request is permitted.
  4. Browser Processes the Response: The browser sees the Access-Control-Allow-Origin header in the response and allows the frontend JavaScript code on Website A to access the response data.

Code Example

Here's what the HTTP headers might look like:

Request from Website A to Website B

GET /data HTTP/1.1
Host: api.website-b.com
Origin: https://websites-a.com

Request from Website A to Website A

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://website-a.com
Content-Type: application/json

{
	"data" : "sample data"
}

Conclusion

In this example, CORS enables Website A to safely and successfully request data from Website B, despite being on different origins. Without CORS, this kind of cross-origin request would be automatically blocked by the browser for security reasons.

 

 

 

OAuth 2.0 문서에 명시되어 있는 규칙이여서 라고 한다.

 

 

참고 문서

https://stackoverflow.com/questions/62075880/why-we-write-bearer-in-front-of-the-token-in-the-authorization-header

https://datatracker.ietf.org/doc/html/rfc6750

 

RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage

This specification describes how to use bearer tokens in HTTP requests to access OAuth 2.0 protected resources. Any party in possession of a bearer token (a "bearer") can use it to get access to the associated resources (without demonstrating possession of

datatracker.ietf.org

 

+ Recent posts