From 5f889de047ccfc8b8a118d2dabdcccb0c84d76b4 Mon Sep 17 00:00:00 2001 From: Terence Honles Date: Fri, 21 Jul 2023 06:46:18 -0700 Subject: [PATCH] Allow swagger to use custom CSRF settings and read the CSRF cookie (#660) --- src/drf_yasg/app_settings.py | 2 ++ src/drf_yasg/renderers.py | 3 +++ src/drf_yasg/static/drf-yasg/swagger-ui-init.js | 17 ++++++++++++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/drf_yasg/app_settings.py b/src/drf_yasg/app_settings.py index dd14fdc8..565a12f5 100644 --- a/src/drf_yasg/app_settings.py +++ b/src/drf_yasg/app_settings.py @@ -41,6 +41,8 @@ 'DEFAULT_API_URL': None, 'USE_SESSION_AUTH': True, + 'CSRF_COOKIE_NAME': settings.CSRF_COOKIE_NAME, + 'CSRF_HEADER_NAME': settings.CSRF_HEADER_NAME, 'SECURITY_DEFINITIONS': { 'Basic': { 'type': 'basic' diff --git a/src/drf_yasg/renderers.py b/src/drf_yasg/renderers.py index 7d79aaf6..cf32cdf7 100644 --- a/src/drf_yasg/renderers.py +++ b/src/drf_yasg/renderers.py @@ -153,6 +153,9 @@ def get_swagger_ui_settings(self): 'refetchWithAuth': swagger_settings.REFETCH_SCHEMA_WITH_AUTH, 'refetchOnLogout': swagger_settings.REFETCH_SCHEMA_ON_LOGOUT, 'fetchSchemaWithQuery': swagger_settings.FETCH_SCHEMA_WITH_QUERY, + 'csrfCookie': swagger_settings.CSRF_COOKIE_NAME, + # remove HTTP_ and convert underscores to dashes + 'csrfHeader': swagger_settings.CSRF_HEADER_NAME[5:].replace('_', '-'), } data = filter_none(data) diff --git a/src/drf_yasg/static/drf-yasg/swagger-ui-init.js b/src/drf_yasg/static/drf-yasg/swagger-ui-init.js index 9606a3be..4ef2fd51 100644 --- a/src/drf_yasg/static/drf-yasg/swagger-ui-init.js +++ b/src/drf_yasg/static/drf-yasg/swagger-ui-init.js @@ -36,11 +36,26 @@ var swaggerUiConfig = { ], layout: "StandaloneLayout", filter: true, + csrfCookie: 'csrftoken', + csrfHeader: 'X-CSRFToken', requestInterceptor: function (request) { var headers = request.headers || {}; var csrftoken = document.querySelector("[name=csrfmiddlewaretoken]"); if (csrftoken) { - headers["X-CSRFToken"] = csrftoken.value; + csrftoken = csrftoken.value; + } else { + var cookies = document.cookie.split(/;\s+/); + var name = swaggerUiConfig.csrfCookie; + for (var i = 0; i < cookies.length; i++) { + if (cookies[i].indexOf(name) === 0) { + csrftoken = cookies[i].slice(cookies[i].indexOf('=') + 1); + break; + } + } + } + + if (csrftoken) { + headers[swaggerUiConfig.csrfHeader] = csrftoken; } return request;