Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions ansible_base/authentication/session.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,31 @@
from django.conf import settings
from rest_framework import authentication

from ansible_base.lib.utils.settings import get_setting


class SessionAuthentication(authentication.SessionAuthentication):
"""
This class allows us to fail with a 401 if the user is not authenticated.
Uses AnsibleBaseCsrfViewMiddleware for CSRF checking instead of Django's
default CsrfViewMiddleware, allowing CSRF_TRUSTED_ORIGINS to be read
dynamically using get_setting.
"""

def authenticate_header(self, request):
return "Session"

def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication using
AnsibleBaseCsrfViewMiddleware instead of Django's CsrfViewMiddleware.
"""
csrf_trusted_origins = settings.CSRF_TRUSTED_ORIGINS
try:
# Temporarily patch the setting
settings.CSRF_TRUSTED_ORIGINS = get_setting("CSRF_TRUSTED_ORIGINS", csrf_trusted_origins)
return super().enforce_csrf(request)
finally:
# Revert setting after this is done
settings.CSRF_TRUSTED_ORIGINS = csrf_trusted_origins
4 changes: 3 additions & 1 deletion test_app/tests/authentication/test_middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from django.conf import settings
from social_core.exceptions import AuthException

from ansible_base.authentication.middleware import SocialExceptionHandlerMiddleware
from ansible_base.authentication.middleware import (
SocialExceptionHandlerMiddleware,
)


def test_social_exception_handler_mw():
Expand Down