CORS가 대체 무엇일까? (feat. SOP)

Node.js에서 CORS 설정

  1. CORS 패키지 설치

    npm i cors
    
  2. 모든 CORS Request 허용하기

    // app.js
    
    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    // 모든 출처 허용 옵션
    // 1.
    app.use(cors());  
    // 2.
    app.use(cors({ origin: '*',}));
    
  3. Whitelist로 특정 주소만 허용하기

    특정 호스트만 CORS 요청을 허용하고 싶다면 whitelist에 허용할 주소를 추가

    app.js
    
    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    const whitelist = ['<http://localhost:3000>'];
    const corsOptions = {
    	origin: function (origin, callback) {
    		if (whitelist.indexOf(origin) !== -1) {
    			callback(null, true);
    		} else {
    			callback(new Error('Not Allowed Origin!'));
    		}
    	},
    };
    
    app.use(cors(corsOptions)); // 옵션을 추가한 CORS 미들웨어 추가
    
    // 쿠키 공유 허용 옵션 (서버 입장) 
    // 쿠키 등 인증정보 공유는 클라이언트에서도 설정 필요
    app.use(cors({
    	origin: true,  // 출처 허용 옵션
    	credential: true  // 사용자 인증이 필요한 리소스(쿠키 ..등) 접근
    }));
    
    let corsOptions = {
        origin: '<https://www.domain.com>',
        credentials: true
    }
    
    app.use(cors(corsOptions));
    
  4. 쿠키 요청 허용

    도메인이 다른 클라이언트가 쿠키 값을 보내고 싶으면, 클라이언트에선 credentials 옵션 설정을 넣어주여야 하고, 서버에서도 cors 설정에서 credentials: true 로 옵션을 둘 다 설정해주어야 한다.

    credentials:true 옵션이란 다른 도메인 간에 쿠키 공유를 허락하는 옵션이다. 서버 간 도메인이 다른 경우 이 옵션을 활성화하지 않으면 로그인되지 않을 수 있다.

    만일 credentail: true로 인증된 요청을 사용할 경우, Access-Control-Allow-Origin 값이 '*' 일 경우 다음 에러가 발생한다.

    Access to XMLHttpRequest at 'http://lahuman.github.io' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

    인증 정보를 포함한 통신시 Access-Control-Allow-Origin 값이 '*' 일 경우 지원을 하지 않는 다는 것이다. 그래서 *credentail옵션을 쓸때는 반드시 허용 출처를 가 아닌 직접 명시를 해주어야 한다.

자료 출처

https://inpa.tistory.com/entry/NODE-📚-CORS-설정하기-cors-모듈

https://handhand.tistory.com/35

참고할 만한 링크

https://hudi.blog/sop-and-cors/