Program Tip

Access-Control-Allow-Origin 헤더는 어떻게 작동합니까?

programtip 2020. 9. 27. 13:46
반응형

Access-Control-Allow-Origin 헤더는 어떻게 작동합니까?


분명히 나는 ​​그 의미를 완전히 오해했습니다. 나는 다음과 같은 것을 생각했다.

  1. 클라이언트는 http : // siteA- the origin 에서 자바 스크립트 코드 MyCode.js를 다운로드 합니다 .
  2. MyCode.js의 응답 헤더에는 Access-Control-Allow-Origin : http : // siteB가 포함되어 있습니다 . 이는 MyCode.js가 사이트 B에 대한 출처 간 참조를 만들 수 있음을 의미한다고 생각했습니다.
  3. 클라이언트는 MyCode.js의 일부 기능을 트리거하여 http : // siteB에 요청을합니다. 이는 교차 출처 요청 임에도 불구하고 괜찮습니다.

글쎄, 내가 틀렸어. 전혀 이와 같이 작동하지 않습니다. 그래서 Cross-origin 리소스 공유 를 읽고 w3c 권장 사항에서 Cross-Origin Resource Sharing 을 읽으려고 시도했습니다.

한 가지는 확실합니다.이 헤더를 어떻게 사용해야하는지 여전히 이해하지 못합니다.

사이트 A와 사이트 B를 모두 제어 할 수 있습니다. 사이트 A에서 다운로드 한 자바 스크립트 코드가이 헤더를 사용하여 사이트 B의 리소스에 액세스 할 수 있도록하려면 어떻게해야합니까?

추신

JSONP를 사용하고 싶지 않습니다.


Access-Control-Allow-OriginA는 CORS (교차 리소스 공유) 헤더 .

사이트 A가 사이트 B에서 콘텐츠를 가져 오려고 할 때 사이트 B는 Access-Control-Allow-Origin브라우저에이 페이지의 콘텐츠를 특정 출처에서 액세스 할 수 있음을 알리는 응답 헤더를 보낼 수 있습니다 . ( 오리진도메인, 스키마 및 포트 번호 입니다.) 기본적으로 사이트 B의 페이지는 다른 오리진에 액세스 할 수 없습니다 . Access-Control-Allow-Origin헤더를 사용하면 특정 요청 출처에 의한 교차 출처 액세스의 문이 열립니다.

사이트 B가 사이트 A에 액세스 할 수 있도록하려는 각 리소스 / 페이지에 대해 사이트 B는 응답 헤더와 함께 페이지를 제공해야합니다.

Access-Control-Allow-Origin: http://siteA.com

최신 브라우저는 도메인 간 요청을 완전히 차단하지 않습니다. 사이트 A가 사이트 B의 페이지를 요청하면 브라우저는 실제로 네트워크 수준 에서 요청 된 페이지 가져와 응답 헤더에 사이트 A가 허용 된 요청자 도메인으로 나열되는지 확인합니다. 사이트 B가 사이트 A가이 페이지에 액세스 할 수 있다고 표시하지 않은 경우 브라우저는 XMLHttpRequesterror이벤트를 트리거 하고 요청하는 JavaScript 코드에 대한 응답 데이터를 거부합니다.

단순하지 않은 요청

네트워크 수준에서 일어나는 일은 위에서 설명한 것보다 약간 더 복잡 할 수 있습니다 . 요청이 "비 단순"요청 인 경우 브라우저는 먼저 데이터가없는 "프리 플라이트"OPTIONS 요청을 전송하여 서버가 요청을 수락하는지 확인합니다. 다음 중 하나 (또는 ​​둘 다) 인 경우 요청이 단순하지 않습니다.

  • GET 또는 POST 이외의 HTTP 동사 사용 (예 : PUT, DELETE)
  • 단순하지 않은 요청 헤더 사용 유일한 간단한 요청 헤더는 다음과 같습니다.
    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type(이 값은 단순한 경우이다 application/x-www-form-urlencoded, multipart/form-data또는 text/plain)

서버 가 비 단순 동사 및 / 또는 비 단순 헤더와 일치하는 적절한 응답 헤더 ( Access-Control-Allow-Headers비 단순 헤더의 경우, Access-Control-Allow-Methods비 단순 동사의 경우) 를 사용하여 OPTIONS 프리 플라이트에 응답 하면 브라우저는 실제 요청을 보냅니다.

사이트 A가에 대한 PUT 요청을 /somePage단순하지 않은 Content-Type으로 보내려고한다고 가정하면 application/json브라우저는 먼저 실행 전 요청을 보냅니다.

OPTIONS /somePage HTTP/1.1
Origin: http://siteA.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type

그 주 Access-Control-Request-MethodAccess-Control-Request-Headers브라우저에 의해 자동으로 추가됩니다; 추가 할 필요가 없습니다. 이 OPTIONS 프리 플라이트는 성공적인 응답 헤더를 가져옵니다.

Access-Control-Allow-Origin: http://siteA.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type

실제 요청을 보낼 때 (프리 플라이트가 완료된 후) 동작은 단순 요청이 처리되는 방식과 동일합니다. 즉, 프리 플라이트가 성공한 단순하지 않은 요청은 단순 요청과 동일하게 처리됩니다 (즉, 서버는 Access-Control-Allow-Origin실제 응답을 위해 다시 전송해야 함 ).

브라우저는 실제 요청을 보냅니다.

PUT /somePage HTTP/1.1
Origin: http://siteA.com
Content-Type: application/json

{ "myRequestContent": "JSON is so great" }

그리고 서버는 Access-Control-Allow-Origin간단한 요청과 마찬가지로를 다시 보냅니다 .

Access-Control-Allow-Origin: http://siteA.com

단순하지 않은 요청에 대한 자세한 정보는 CORS통한 XMLHttpRequest 이해를 참조하십시오 .


Cross-Origin Request Sharing- CORS(일명 Cross-Domain AJAX 요청)은 대부분의 웹 개발자가 겪을 수있는 문제입니다. Same-Origin-Policy에 따르면 브라우저는 보안 샌드 박스에서 클라이언트 JavaScript를 제한하며 일반적으로 JS는 원격 서버와 직접 통신 할 수 없습니다. 다른 도메인에서. 과거에 개발자는 도메인 간 리소스 요청을 달성하기 위해 여러 가지 까다로운 방법을 만들었으며 가장 일반적으로 사용하는 방법은 다음과 같습니다.

  1. Flash / Silverlight 또는 서버 측을 "프록시"로 사용하여 원격과 통신합니다.
  2. 패딩이있는 JSON ( JSONP ).
  3. iframe에 원격 서버를 포함하고 fragment 또는 window.name을 통해 통신 합니다 . 여기를 참조 하세요 .

이러한 까다로운 방법에는 다소 문제가 있습니다. 예를 들어 JSONP는 개발자가 단순히 "평가"하면 보안 허점을 초래할 수 있으며 위의 # 3은 작동하지만 작동하지만 두 도메인은 서로간에 엄격한 계약을 구축해야하며 유연하지도 우아하지도 않습니다. IMHO :)

W3C는이 문제를 해결하기 위해 안전하고 유연하며 권장되는 표준 방법을 제공하기 위해 CORS (Cross-Origin Resource Sharing)를 표준 솔루션으로 도입했습니다.

메커니즘

높은 수준에서 CORS가 도메인 A의 클라이언트 AJAX 호출과 도메인 B에서 호스팅되는 페이지 간의 계약이라고 생각할 수 있습니다. 일반적인 Cross-Origin 요청 / 응답은 다음과 같습니다.

DomainA AJAX 요청 헤더

Host DomainB.com
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
Accept-Language en-us;
Accept-Encoding gzip, deflate
Keep-Alive 115
Origin http://DomainA.com 

DomainB 응답 헤더

Cache-Control private
Content-Type application/json; charset=utf-8
Access-Control-Allow-Origin DomainA.com
Content-Length 87
Proxy-Connection Keep-Alive
Connection Keep-Alive

위에 표시 한 파란색 부분은 커널 사실입니다. "Origin"요청 헤더는 "교차 출처 요청 또는 프리 플라이트 요청이 시작된 위치를 나타냅니다.", "Access-Control-Allow-Origin"응답 헤더는이 페이지에서 원격 요청을 허용 함을 나타냅니다. DomainA (값이 *이면 모든 도메인의 원격 요청을 허용 함을 나타냄).

위에서 언급했듯이 W3 는 실제로 Cross-Origin HTTP 요청을 제출하기 전에 " 프리 플라이트 요청 " 을 구현하도록 브라우저를 권장 했습니다. 간단히 말해서 HTTP OPTIONS요청입니다.

OPTIONS DomainB.com/foo.aspx HTTP/1.1

foo.aspx가 OPTIONS HTTP 동사를 지원하는 경우 아래와 같은 응답을 반환 할 수 있습니다.

HTTP/1.1 200 OK
Date: Wed, 01 Mar 2011 15:38:19 GMT
Access-Control-Allow-Origin: http://DomainA.com
Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
Access-Control-Allow-Headers: X-Requested-With
Access-Control-Max-Age: 1728000
Connection: Keep-Alive
Content-Type: application/json

응답에 "Access-Control-Allow-Origin"이 포함되고 해당 값이 "*"이거나 CORS 요청을 제출 한 도메인이 포함 된 경우에만이 필수 조건을 충족하여 브라우저가 실제 교차 도메인 요청을 제출하고 결과를 캐시합니다. " Preflight-Result-Cache "에서.

3 년 전에 CORS에 대해 블로그에 올렸습니다. AJAX Cross-Origin HTTP 요청


질문은 답변하기에는 너무 오래되었지만이 질문에 대한 향후 참조를 위해 게시하고 있습니다.

Mozilla 개발자 네트워크 기사 에 따르면

리소스는 첫 번째 리소스 자체가 제공하는 것과 다른 도메인 또는 포트에서 리소스를 요청할원본 간 HTTP 요청을 합니다.

enter image description here

An HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg.
Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains (thus it should be cool).

Same-Origin Policy

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.
For example, XMLHttpRequest and Fetch follow the same-origin policy.
So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.

Cross-Origin Resource Sharing (CORS)

To improve web applications, developers asked browser vendors to allow cross-domain requests.

The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.
Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.

How CORS works (Access-Control-Allow-Origin header)

Wikipedia:

The CORS standard describes new HTTP headers which provide browsers and servers a way to request remote URLs only when they have permission.

Although some validation and authorization can be performed by the server, it is generally the browser's responsibility to support these headers and honor the restrictions they impose.

Example

  1. The browser sends the OPTIONS request with an Origin HTTP header.

    The value of this header is the domain that served the parent page. When a page from http://www.example.com attempts to access a user's data in service.example.com, the following request header would be sent to service.example.com:

    Origin: http://www.example.com

  2. The server at service.example.com may respond with:

    • An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed.
      For example:

      Access-Control-Allow-Origin: http://www.example.com

    • An error page if the server does not allow the cross-origin request

    • An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains:

      Access-Control-Allow-Origin: *


Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.

The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.

Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainA.com, using the Access-Control-Allow-Origin header to list other domains (domainB.com) that are trusted to run JavaScript that can interact with domainA.com.

To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.

I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?


Using React and Axios, join proxy link to the URL and add header as shown below

https://cors-anywhere.herokuapp.com/ + Your API URL

Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.

axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
      .then(response => console.log(response:data);
  }

If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe. From MAC OS you can do this from the terminal line:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

1. A client downloads javascript code MyCode.js from http://siteA - the origin.

The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)

2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.

no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.

Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.


i work with express 4 and node 7.4 and angular,I had the same problem me help this:
a) server side: in file app.js i give headers to all response like:

app.use(function(req, res, next) {  
      res.header('Access-Control-Allow-Origin', req.headers.origin);
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
 });  

this must have before all router.
I saw a lot of added this headers:

res.header("Access-Control-Allow-Headers","*");
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');

but i dont need that,
b) client side: in send ajax you need add: "withCredentials: true," like:

$http({
     method: 'POST',
     url: 'url, 
     withCredentials: true,
     data : {}
   }).then(function(response){
        // code  
   }, function (response) {
         // code 
   });

good luck.


If you are using PHP, try adding the following code at the beginning of the php file:

If you are using localhost, try this:

header("Access-Control-Allow-Origin: *");

If you are using external domains such as server, try this:

header("Access-Control-Allow-Origin: http://www.website.com");

In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.

Installing:

$ pip install -U flask-cors

Simple example that allows CORS for all domains on all routes:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.


For cross origin sharing, set header: 'Access-Control-Allow-Origin':'*';

Php: header('Access-Control-Allow-Origin':'*');

Node: app.use('Access-Control-Allow-Origin':'*');

This will allow to share content for different domain.


Simply paste the following code in your web.config file.

Noted that, you have to paste the following code under <system.webServer> tag

    <httpProtocol>  
    <customHeaders>  
     <add name="Access-Control-Allow-Origin" value="*" />  
     <add name="Access-Control-Allow-Headers" value="Content-Type" />  
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />  
    </customHeaders>  
  </httpProtocol>  

The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin.

Header type Response       header
Forbidden header name      no

A response that tells the browser to allow code from any origin to access a resource will include the following:

Access-Control-Allow-Origin: *

For more info, visit here....

참고URL : https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work

반응형