Skip to content

Instantly share code, notes, and snippets.

@monokrome
Created September 21, 2011 05:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monokrome/1231326 to your computer and use it in GitHub Desktop.
Save monokrome/1231326 to your computer and use it in GitHub Desktop.
CORS middleware for Django
import re
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
from django.conf import settings
from django import http
XS_SHARING_ALLOWED_ORIGINS = getattr(settings, 'XS_SHARING_ALLOWED_ORIGINS', ['*'])
XS_SHARING_ALLOWED_METHODS = getattr(settings, 'XS_SHARING_ALLOWED_METHODS', [
'POST',
'GET',
'OPTIONS',
'PUT',
'DELETE'
])
class XsSharing(object):
""" Allows cross-domain XHR using the html5 postMessage API. """
def process_request(self, request):
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
if 'HTTP_ORIGIN' in request.META:
if request.META['HTTP_ORIGIN'] in XS_SHARING_ALLOWED_ORIGINS or '*' in XS_SHARING_ALLOWED_ORIGINS:
response = http.HttpResponse()
response['Access-Control-Allow-Origin'] = request.META['HTTP_ORIGIN']
response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS)
return response
return None
def process_response(self, request, response):
if response.has_header('Access-Control-Allow-origin'):
return response
if 'HTTP_ORIGIN' in request.META:
if request.META['HTTP_ORIGIN'] in XS_SHARING_ALLOWED_ORIGINS or '*' in XS_SHARING_ALLOWED_ORIGINS:
response['Access-Control-Allow-Origin'] = request.META['HTTP_ORIGIN']
response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS)
return response
~
Copy link

ghost commented Oct 17, 2013

The "Access-Control-Allow-Headers" header is not set during a preflight OPTIONS request.
The snippet below can be added between line 28 and 29 to fix that. Sure, it can be configured via the settings file
as well like you already have for the other two headers.
response['Access-Control-Allow-Headers'] = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment