简体   繁体   中英

Django 1.10: login required middleware redirect loop

I'm writing a bit of middleware to effectively make @login_required on all pages. Unfortunately what I've got results in a redirect loop.

The implementation is using "old" style middleware with 1.10 via MiddlewareMixin and process_request() hook in attempt to redirect to login page whenever the user is not authenticated.

First, I'm using the default auth urls django.contrib.auth.urls . The docs say:

This will include the following URL patterns: ^login/$ [name='login'] ...

# main URLConf urls.py
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('django.contrib.auth.urls')),  # https://docs.djangoproject.com/en/1.10/topics/auth/default/#module-django.contrib.auth.views
]

Then here's the middleware (yes it's added to MIDDLEWARE in settings.py ):

from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin

class LoginRequiredMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect('/login/')

The login page/functionality works fine when the my middleware isn't included, while including it results in every url causing ERR_TOO_MANY_REDIRECTS .

What am I missing? Thanks.

Doh! I needed to check for /login/ in process_request and ignore it.

Here's a simplified version of what is implemented. The real version uses settings.py and regexes to define the login exempt urls. Much credit to Ryan Witt's post on this approach.

class LoginRequiredMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            # If path is not root url ('') and path is not exempt from authentication
            if not path or not any(path != eu for eu in ["/login", "admin"]):
                return HttpResponseRedirect("/login/")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM