Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Middlware to allow's your django server to respond appropriately to cross domain XHR (postMessage html5 API).
import re
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
from django import http
try:
import settings
XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
except:
XS_SHARING_ALLOWED_ORIGINS = '*'
XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']
class XsSharing(object):
"""
This middleware allows cross-domain XHR using the html5 postMessage API.
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
"""
def process_request(self, request):
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
response = http.HttpResponse()
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
return response
return None
def process_response(self, request, response):
# Avoid unnecessary work
if response.has_header('Access-Control-Allow-Origin'):
return response
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
return response
@timsloan

This comment has been minimized.

Show comment Hide comment
@timsloan

timsloan Nov 24, 2010

Thanks. This helped a lot.

Thanks. This helped a lot.

@sandinmyjoints

This comment has been minimized.

Show comment Hide comment
@sandinmyjoints

sandinmyjoints Oct 4, 2011

This is great, thanks!

This is great, thanks!

@jessykate

This comment has been minimized.

Show comment Hide comment
@jessykate

jessykate Jun 16, 2012

awesome, thanks a lot!

awesome, thanks a lot!

@axelpale

This comment has been minimized.

Show comment Hide comment
@axelpale

axelpale Jul 29, 2012

Very nice, thank you! If I must say something constructive, I would name the class to XsSharingMiddleware. Middleware-postfix seems to be the convention amongst Django middlewares. For example: 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'. And what does Xs mean? Anyway, thanks for the gist, I will put it to good use :)

Very nice, thank you! If I must say something constructive, I would name the class to XsSharingMiddleware. Middleware-postfix seems to be the convention amongst Django middlewares. For example: 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'. And what does Xs mean? Anyway, thanks for the gist, I will put it to good use :)

@barrabinfc

This comment has been minimized.

Show comment Hide comment
@barrabinfc

barrabinfc Aug 5, 2012

Thanks @doph. I will rewrite, but anyway, i'm not working with django anymore for a long time, so if you want to fork and maintain this snippet updated with django, i will appreciate a lot!

The "xs" suffix was just a "gotcha" with XSS. I could name it XssSharing , but i prefer to let the last 's' mixed with sharing. You can rename as you like.

Owner

barrabinfc commented Aug 5, 2012

Thanks @doph. I will rewrite, but anyway, i'm not working with django anymore for a long time, so if you want to fork and maintain this snippet updated with django, i will appreciate a lot!

The "xs" suffix was just a "gotcha" with XSS. I could name it XssSharing , but i prefer to let the last 's' mixed with sharing. You can rename as you like.

@jessykate

This comment has been minimized.

Show comment Hide comment
@jessykate

jessykate Aug 5, 2012

@doph @frangossauro i've been using this awesome gist and customized it a bit to support allowed headers, which i needed to make CORS work for my project. you can see my fork here: https://gist.github.com/2941258

@doph @frangossauro i've been using this awesome gist and customized it a bit to support allowed headers, which i needed to make CORS work for my project. you can see my fork here: https://gist.github.com/2941258

@nybatista

This comment has been minimized.

Show comment Hide comment
@nybatista

nybatista Oct 26, 2012

made my day. thanks alot

made my day. thanks alot

@ondrejsika

This comment has been minimized.

Show comment Hide comment
@ondrejsika

ondrejsika Sep 22, 2013

Thanks

Thanks

@manuganji

This comment has been minimized.

Show comment Hide comment
@manuganji

manuganji Feb 11, 2014

Thanks for this! :)

Thanks for this! :)

@Sascuash

This comment has been minimized.

Show comment Hide comment
@Sascuash

Sascuash Mar 13, 2014

Thanks, that's really helpful.

Quick question: What changes should I make in order to allow certain urls of my site to be "open" for cors?

Thanks, that's really helpful.

Quick question: What changes should I make in order to allow certain urls of my site to be "open" for cors?

@Mbrownshoes

This comment has been minimized.

Show comment Hide comment
@Mbrownshoes

Mbrownshoes May 22, 2014

I'm trying to get this going but still get this error when I load my site

XMLHttpRequest cannot load http://localhost:8080/geoserver/wfs. Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.

My settings.py file
XS_SHARING_ALLOWED_ORIGINS = 'http://localhost:8080, http://127.0.0.1:8000/'
XS_SHARING_ALLOWED_METHODS = "POST, GET, OPTIONS, PUT, DELETE"

Any help would be greatly appreciated!

I'm trying to get this going but still get this error when I load my site

XMLHttpRequest cannot load http://localhost:8080/geoserver/wfs. Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.

My settings.py file
XS_SHARING_ALLOWED_ORIGINS = 'http://localhost:8080, http://127.0.0.1:8000/'
XS_SHARING_ALLOWED_METHODS = "POST, GET, OPTIONS, PUT, DELETE"

Any help would be greatly appreciated!

@ozen

This comment has been minimized.

Show comment Hide comment
@ozen

ozen Jun 20, 2014

@Mbrownshoes multiple origins are not allowed. I changed XS_SHARING_ALLOWED_ORIGINS into a list and add the following code to the middleware:

        if 'HTTP_ORIGIN' in request.META:
            for origin in settings.XS_SHARING_ALLOWED_ORIGINS:
                if origin == request.META['HTTP_ORIGIN']:
                    response['Access-Control-Allow-Origin'] = origin
                    break

It looks into the list and add the allowed-origin header only for the current origin if it is in the list.

ozen commented Jun 20, 2014

@Mbrownshoes multiple origins are not allowed. I changed XS_SHARING_ALLOWED_ORIGINS into a list and add the following code to the middleware:

        if 'HTTP_ORIGIN' in request.META:
            for origin in settings.XS_SHARING_ALLOWED_ORIGINS:
                if origin == request.META['HTTP_ORIGIN']:
                    response['Access-Control-Allow-Origin'] = origin
                    break

It looks into the list and add the allowed-origin header only for the current origin if it is in the list.

@adrihein

This comment has been minimized.

Show comment Hide comment
@adrihein

adrihein Jun 29, 2014

Wonderful, thank you.

Wonderful, thank you.

@Roryjia

This comment has been minimized.

Show comment Hide comment
@Roryjia

Roryjia Dec 2, 2016

@ozen work for me , thanks !

Roryjia commented Dec 2, 2016

@ozen work for me , thanks !

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