chapter seventeen

17 Cross-origin resource sharing

 

This chapter covers

  • Understanding the same-origin policy
  • Sending and receiving simple CORS requests
  • Implementing CORS with django-cors-headers
  • Sending and receiving preflighted CORS requests

In a previous chapter you learned that an origin is defined by the protocol (scheme), host, and port of a URL. Every browser implements a same-origin policy (SOP). The goal of this policy is to ensure that certain resources are accessible to documents with only the “same origin.” This prevents a page with an origin of mallory.com from gaining unauthorized access to a resource with an origin of ballot.charlie.com.

Think of Cross-Origin Resource Sharing (CORS) as a way to relax the browser’s SOP. This allows social.bob.com to load a font from https://fonts.gstatic.com. It also lets a page from alice.com send an AJAX request to social.bob.com. In this chapter I show you how to safely create and consume shared resources with django-cors-headers. Due to the nature of CORS, this chapter contains more JavaScript than Python.

17.1       Same-origin policy

By now you’ve seen Mallory gain unauthorized access to many different resources. She cracked Charlie’s password with a rainbow table. She took over Bob’s account with a Host header attack. She figured out who Alice voted for with XSS. In this section Mallory launches a much simpler attack.

17.2       Simple CORS requests

17.2.1   Cross-origin AJAX requests

17.3       CORS with django-cors-headers

17.3.1   Configuring Access-Control-Allow-Origin

17.4       Preflight CORS requests

17.4.1   Sending the preflight request

17.4.2   Sending the preflight response

17.5       Sending cookies across origins

17.6       CORS and CSRF resistance

17.7       Summary