diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 9662bd2a..73d59679 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -13,10 +13,6 @@ jobs: - name: Checkout the source code uses: actions/checkout@v4 - # This is the version of python used to package the code. The unit - # tests will have run against python 3.6, 3.7 etc ensuring - # compatibility with those runtimes. - # https://github.com/axnsan12/drf-yasg/pull/741#discussion_r713297594 - name: Set the python version uses: actions/setup-python@v5 with: 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;