Cross-Origin Resource Sharing
기본적으로 브라우저는 보안상의 이유로, 클라이언트가 존재하는 도메인과 다른 도메인에 존재하는 서버로 접근하는 것을 막는다.
그러나 현대에서는 css, font, Image등을 다른 서버로부터 받아오는 경우가 허다하고, 일반적으로 쓰여지는 Rest API 또한 하나의 어플리케이션만을 지원하지 않는다. 이러한 리소스들을 사용할 때, 서버에서 헤더 값을 통해 cross-domain을 허용해주지 않으면 브라우저에서 오류가 발생한다.
CORS는 추가적인 HTTP 헤더 값들을 통해 브라우저에게 괜찮다고, 접근해도 된다고 안심시켜주는 메커니즘이라고 볼 수 있겠다.
CORS는 크게 두가지 경우로 나뉜다. Preflighted requests 같은 경우에는, 서버로 요청을 보내기 전에 OPTIONS TYPE의 요청을 먼저 한 번 보낸 후에 본격적인 요청을 시작한다.
- Simple requests: 세 가지 조건을 만족해야한다.
- GET, HEAD, POST 중 한 가지
- POST 방식일 경우 Content-type이 아래 셋 중의 하나
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
- 커스텀 헤더(Authorization 포함)을 보내지 말야아 한다.
-
Preflighted requests: Simple requests가 적용되지 않는 경우, HTTP OPTIONS method를 통해 예비 요청을 보내고, 서버에서는 이 예비 요청에 대한 응답으로 현재 자신이 어떤 것들을 허용하고, 어떤 것들을 금지하고 있는지에 대한 정보를 응답 헤더에 담아서 브라우저에게 다시 보내주게 된다. 이 후 브라우저가 안전성을 판단하고 본 요청을 보내게 된다.
- Credentialed requests: 브라우저가 제공하는 XMLHttpRequest 객체나 fetch API는 기본적으로 별도의 옵션 없이 브라우저의 쿠키 정보나 인증과 관련된 헤더를 요청에 담지 않는다.Credentialed requests는 HTTP Cookie와 HTTP Authentication 정보를 인식할 수 있게 해주는 요청이다. credential 옵션을 사용할 경우, Access-Control-Allow-Origin에 *를 넣을 수 없고 명시적인 URL을 써야한다.
- same-origin (기본값) 같은 출처 간 요청에만 인증 정보를 담을 수 있다
- include 모든 요청에 인증 정보를 담을 수 있다
- omit 모든 요청에 인증 정보를 담지 않는다
헤더에 추가해주는 것들
- Origin: this header is used by the client to specify which domain the request is executed from. The server uses this hint to authorize, or not, the cross-domain request.
- Access-Control-Request-Method: with in the context of preflighted requests, the OPTIONS request sends this header to check if the target method is allowed in the context of cross-domain requests.
- Access-Control-Request-Headers: with in the context of preflighted requests, the OPTIONS request sends this header to check if headers are allowed for the target method in the context of cross-domain requests.
- Access-Control-Allow-Credentials: this specifies if credentials are supported for cross-domain requests.
- Access-Control-Allow-Methods: the server uses this header to tell which headers are authorized in the context of the request. This is typically used in the context of preflighted requests.
- Access-Control-Allow-Origin: the server uses this header to tell which domains are authorized for the request.
- Access-Control-Allow-Headers: the server uses this header to tell which headers are authorized in the context of the request. This is typically used in the context of preflighted requests.
Resource
https://www.youtube.com/watch?v=zoSJ3bNGPp0 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests http://restlet.com/company/blog/2015/12/15/understanding-and-using-cors/