From b76984d222281e58e3105df0128141567b9a7697 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 18 Aug 2016 11:24:03 +0100 Subject: [PATCH] Allow custom CSRF_HEADER_NAME setting. (#4415) --- rest_framework/renderers.py | 9 ++++++++- rest_framework/static/rest_framework/js/csrf.js | 2 +- rest_framework/templates/rest_framework/admin.html | 1 + rest_framework/templates/rest_framework/base.html | 1 + 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 371cd6ec7..11e9fb960 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -645,6 +645,12 @@ class BrowsableAPIRenderer(BaseRenderer): else: paginator = None + csrf_cookie_name = settings.CSRF_COOKIE_NAME + csrf_header_name = getattr(settings, 'CSRF_HEADER_NAME', 'HTTP_X_CSRFToken') # Fallback for Django 1.8 + if csrf_header_name.startswith('HTTP_'): + csrf_header_name = csrf_header_name[5:] + csrf_header_name = csrf_header_name.replace('_', '-') + context = { 'content': self.get_content(renderer, data, accepted_media_type, renderer_context), 'view': view, @@ -675,7 +681,8 @@ class BrowsableAPIRenderer(BaseRenderer): 'display_edit_forms': bool(response.status_code != 403), 'api_settings': api_settings, - 'csrf_cookie_name': settings.CSRF_COOKIE_NAME, + 'csrf_cookie_name': csrf_cookie_name, + 'csrf_header_name': csrf_header_name } return context diff --git a/rest_framework/static/rest_framework/js/csrf.js b/rest_framework/static/rest_framework/js/csrf.js index f8ab4428c..97c8d0124 100644 --- a/rest_framework/static/rest_framework/js/csrf.js +++ b/rest_framework/static/rest_framework/js/csrf.js @@ -46,7 +46,7 @@ $.ajaxSetup({ // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier - xhr.setRequestHeader("X-CSRFToken", csrftoken); + xhr.setRequestHeader(window.drf.csrfHeaderName, csrftoken); } } }); diff --git a/rest_framework/templates/rest_framework/admin.html b/rest_framework/templates/rest_framework/admin.html index 89af81ef7..eb2b8f1c7 100644 --- a/rest_framework/templates/rest_framework/admin.html +++ b/rest_framework/templates/rest_framework/admin.html @@ -232,6 +232,7 @@ {% block script %} diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index 4c1136087..989a086ea 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -263,6 +263,7 @@ {% block script %}