Skip to content

Instantly share code, notes, and snippets.

@miratcan
Forked from gkmngrgn/gist:8483510
Created January 17, 2014 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miratcan/8483566 to your computer and use it in GitHub Desktop.
Save miratcan/8483566 to your computer and use it in GitHub Desktop.
from django.conf import settings
from django.http.request import validate_host
from django.middleware.csrf import _sanitize_token, constant_time_compare
from tastypie.authorization import ReadOnlyAuthorization
from tastypie.authentication import Authentication
from urlparse import urlparse
class InternalResourceAuthentication(Authentication):
def is_authenticated(self, request, **kwargs):
# you maybe want to visit api url directly in development process:
if not settings.DEBUG:
# check request type:
if not request.is_ajax():
return False
# check referer:
if not self.validate_referer(request):
return False
# check csrf token:
csrf_token = _sanitize_token(
request.COOKIES.get(settings.CSRF_COOKIE_NAME, ''))
request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
if not constant_time_compare(request_csrf_token, csrf_token):
return False
return super(InternalResourceAuthentication, self).is_authenticated(
request, **kwargs)
def validate_referer(self, request):
referer = request.META.get('HTTP_REFERER')
if referer is None:
return False
parsed_url = urlparse(referer)
return validate_host(parsed_url.hostname, settings.ALLOWED_HOSTS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment