Using new DJ5.1 LoginRequiredMiddleware with login_not_required erroneously redirects API call to login-page #9503
Replies: 3 comments
-
I'm not sure this is the best solution, but you can create a custom middleware that bypasses # app/middleware.py
from django.conf import settings
from django.contrib.auth.middleware import LoginRequiredMiddleware
from django.utils.deprecation import MiddlewareMixin
import re
class CustomLoginRequiredMiddleware(LoginRequiredMiddleware):
def __init__(self, get_response=None):
self.get_response = get_response
self.open_urls = [re.compile(url) for url in settings.OPEN_URLS]
super().__init__(get_response)
def process_view(self, request, view_func, view_args, view_kwargs):
for url in self.open_urls:
if url.match(request.path):
return None # Pass through, no login required
return super().process_view(request, view_func, view_args, view_kwargs) In # app/settings.py
MIDDLEWARE = [
# ...
"app.middleware.CustomLoginRequiredMiddleware",
]
# Regex patterns for paths that bypass LoginRequiredMiddleware
OPEN_URLS = [
r"^/my-api/.*",
# ...
] I'm also very interested in opinions and solutions. |
Beta Was this translation helpful? Give feedback.
-
As far as I understand, it's because Django django-rest-framework/rest_framework/views.py Lines 385 to 397 in 337ba21 django-rest-framework/rest_framework/request.py Lines 378 to 395 in 8e304e1
I would be curious if you see the same behaviour with session auth. My expectation is that it would work, because this relies on a Django built-in auth mechanism, while the others (Basic and token based auth) are DRF specific. With regards to solutions, one might be for DRF to provide a specialized version of Django's |
Beta Was this translation helpful? Give feedback.
-
I've dug this a bit more to attempt to add compatibility to DRF as part of #9514 and just realised that DRF already offers a way to make sure all endpoints are authenticated, via the |
Beta Was this translation helpful? Give feedback.
-
Using the new Django 5.1
LoginRequiredMiddleware
, I ran into an issue with calling an API that uses Basic Authentication. It suddenly kept redirecting to the login-page.So I marked my API call with
@login_not_required
, only to find the problem remained!Moving the
@login_not_required
decorator to the top (setting it as the first decorator, before@api_view(['GET'])
), circumvented the problem.But this seems very ugly. With the need to set the
@login_not_required
decorator on all API's, and more importantly, having to know it needs to be first.I'm of the opinion API-calls should never redirect to a login-page, but rather return the appropriate http-statuscode.
But, where (and how) to implement this?
Very interested in your opinions/solutions.
Beta Was this translation helpful? Give feedback.
All reactions