Skip to content

Commit d9ad639

Browse files
committed
Add DRFSessionAuthentication401Middleware
1 parent 1964929 commit d9ad639

File tree

3 files changed

+119
-38
lines changed

3 files changed

+119
-38
lines changed

django_utils_lib/middleware.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,21 @@ def __call__(self, request: HttpRequest) -> HttpResponse:
8888
response["Location"] = redirect_url.geturl()
8989

9090
return response
91+
92+
93+
try:
94+
from rest_framework.authentication import SessionAuthentication
95+
from rest_framework.request import Request as DRFRequest
96+
97+
class DRFSessionAuthentication401Middleware(SessionAuthentication):
98+
"""
99+
Small shim around DRF's SessionAuthentication, so it returns 401s for
100+
unauthorized, instead of 403.
101+
102+
https://github.com/encode/django-rest-framework/issues/5968
103+
"""
104+
105+
def authenticate_header(self, request: DRFRequest):
106+
return "Session"
107+
except ImportError:
108+
pass

poetry.lock

Lines changed: 99 additions & 38 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ pytest-playwright = "^0.5.2"
2525
filelock = "^3.16.0"
2626
debugpy = "^1.8.5"
2727
django = "*"
28+
djangorestframework = "^3.15.2"
29+
djangorestframework-stubs = {extras = ["compatible-mypy"], version = "^3.15.2"}
2830

2931
[tool.ruff]
3032
line-length = 120

0 commit comments

Comments
 (0)