Skip to content

Instantly share code, notes, and snippets.

@rhblind
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save rhblind/f473db45ed0b28c87d70 to your computer and use it in GitHub Desktop.

Select an option

Save rhblind/f473db45ed0b28c87d70 to your computer and use it in GitHub Desktop.
Django CORS Header setup
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
class SetRemoteAddrFromForwardedFor(object):
"""
Middleware that sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, if the
latter is set. This is useful if you're sitting behind a reverse proxy that
causes each request's REMOTE_ADDR to be set to 127.0.0.1.
Note that this does NOT validate HTTP_X_FORWARDED_FOR. If you're not behind
a reverse proxy that sets HTTP_X_FORWARDED_FOR automatically, do not use
this middleware. Anybody can spoof the value of HTTP_X_FORWARDED_FOR, and
because this sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, that means
anybody can "fake" their IP address. Only use this when you can absolutely
trust the value of HTTP_X_FORWARDED_FOR.
NOTE: This is backported from Django 1.1, and was removed because it's not
reliable! But we're still using it ;)
"""
@staticmethod
def process_request(request):
if "HTTP_X_FORWARDED_FOR" in request.META:
# Always use HTTP_X_FORWARDED_FOR if present.
# HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. The
# client's IP will be the first one.
real_ip = request.META["HTTP_X_FORWARDED_FOR"]
real_ip = real_ip.split(",")[0].strip()
request.META["REMOTE_ADDR"] = real_ip
elif not request.META["REMOTE_ADDR"]:
raise ImproperlyConfigured("Could not read request.META['REMOTE_ADDR'] or "
"request.META['HTTP_X_FORWARDED_FOR']. Unable to determine IP address."
"If you are using a unix socket proxy setup, make sure to set "
"'HTTP_X_FORWARDED_FOR' in order to determine IP address.")
return None
INSTALLED_APPS = (
--snip--
'corsheaders',
--snip--
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', <--- INSERT THIS
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
#
# Django CORS Headers settings
#
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/.*$'
CORS_ALLOW_CREDENTIALS = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment