Skip to content

Commit

Permalink
Allow swagger to use custom CSRF settings and read the CSRF cookie (#660
Browse files Browse the repository at this point in the history
)
  • Loading branch information
terencehonles authored Jul 21, 2023
1 parent c1c25ee commit 5f889de
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/drf_yasg/app_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
3 changes: 3 additions & 0 deletions src/drf_yasg/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 16 additions & 1 deletion src/drf_yasg/static/drf-yasg/swagger-ui-init.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 5f889de

Please sign in to comment.