Understanding CORS Prototype: Examples and Implementation

Table of Contents

CORS Prototype

CORS enabled URLs

Examples

Response Headers

Scaffold

<html>
  <head><title>CORS Example</title></head>
  <body>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script src="cors-ajax.js">
    </script>
    <p>Run from jwalsh.net.  Pulls from remote wal.sh.</p>
    <p>Expect: When run from jwalsh.net (rather than the hosting
    wal.sh) text should be rendered below.</p>
    <pre id="content">
    </pre>
  </body>
</html>

XHR

$.ajax(
  {
    url: 'http://wal.sh/poc/cors/bm/the-third-part-of-king-henry-the-sixth.php',
    data: { debug: 'true' },
    method: 'GET',
    success: function(data) {
      $('#content').html(data);
    },
    beforeSend: function(xhr){
      xhr.withCredentials = true;
    }
  });

Logs

This generates the following requests:

24.22.232.77 - - [28/Sep/2012:02:24:18 -0700] "GET /poc/cors/bm/the-third-part-of-king-henry-the-sixth.php HTTP/1.1" 200 168855 "-" "curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5"
24.22.232.77 - - [28/Sep/2012:02:33:55 -0700] "GET /poc/cors/bm/the-third-part-of-king-henry-the-sixth.php?debug=true HTTP/1.1" 200 66393 "http://jwalsh.net/projects/cors/pull-remote-via-xhr-cors.html" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"

Background

..there is nothing you have to do to make CORS-enabled cross-origin
requests work, there are a few security details worth understanding.
First, if you pass a username and password to the XMLHttpRequest
open() method, they will never be sent with a cross-origin request
(that would enable distributed password-cracking attempts). In
addition, cross-origin requests do not normally include any other user
credentials either: cookies and HTTP authentication tokens are not
normally sent as part of the request and any cookies received as part
of a cross-origin response are discarded. If your cross-origin request
requires these kinds of credentials to succeed, you must set the
withCredentials property of the XMLHttpRequest to true before you
send() the request.[fn:1]

Author: Jason Walsh

j@wal.sh

Last Updated: 2024-10-30 16:43:54