1. Crossing the Domain
a hasty introduction to Cross-origin Resource Sharing (CORS)
Owen Zanzal and Steve Johnson for CV.JS 5/8/2013
Thursday, May 9, 13
3. Let Freedom Ring
• These domains are mine!
• I had to use a different hostname!
• I need this application to work!
Thursday, May 9, 13
4. We have /OPTIONS
• JSONP
• Server-side proxy
• CORS!
• Elaborate iFrame hacks
• postMessage
• Window.name transport
Thursday, May 9, 13
5. JSONP
• JavaScript Object Notation with Padding
• <script> tags not subject to Same-Origin Policy
• You can’t run scripts across domains but you can download
resources
• Download a “Script” from the other site... which happens to
contain data when you execute it
Thursday, May 9, 13
10. CORS
defines a mechanism to enable client-side cross-origin requests.
Specifications that enable an API to make cross-origin requests
to resources can use the algorithms defined by this specification.
If such an API is used on http://example.org resources, a
resource on http://hello-world.example can opt in using the
mechanism described by this specification
http://www.w3.org/TR/cors/
Thursday, May 9, 13
11. CORS browser support
• Chrome 3+ (XMLHttpRequest2)
• Firefox 3.5+ (XMLHttpRequest2)
• Opera 12+ (XMLHttpRequest2)
• Safari 4+ (XMLHttpRequest2)
• Internet Explorer 8+ (XDomainRequest)
http://caniuse.com/#search=cors
http://enable-cors.org/client.html
Thursday, May 9, 13
20. Not Simple: Request
var url = 'http://api.alice.com/cors';
var xhr = createCORSRequest('PUT', url);
xhr.setRequestHeader(
'X-Custom-Header', 'value');
xhr.send();
Thursday, May 9, 13
21. Not Simple: Preflight Request
OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
Thursday, May 9, 13
22. Not Simple: Preflight Response
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Content-Type: text/html; charset=utf-8
Thursday, May 9, 13
23. PROS CONS
web server can opt-in 30-40% of the internet can’t use it
finer-grain control over access Not super-secure
straight up XHR extra complicated headers
Thursday, May 9, 13
24. CORS in ACTION
• http://arunranga.com/examples/access-control/
• Owen’s App!
Thursday, May 9, 13