Django 1.8自定义Token中间件设置后request.user为空问题求助
Let's walk through the possible issues here and fix them step by step:
1. Middleware Order Conflict (Most Likely Culprit)
Looking at your MIDDLEWARE_CLASSES configuration, the django.contrib.auth.middleware.AuthenticationMiddleware runs after your TokenAuthenticationMiddleware.
This built-in middleware’s job is to load the user from the session. If no valid session exists, it sets request.user to an AnonymousUser (what you’re seeing as "Null"). So even if your middleware correctly sets request.user, the subsequent AuthenticationMiddleware overwrites it.
Fix: Move your TokenAuthenticationMiddleware to run after AuthenticationMiddleware so your user assignment takes precedence:
MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'myproject.middleware.MongoAuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # Run built-in auth first 'myproject.middleware.TokenAuthenticationMiddleware', # Then your middleware to overwrite user 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
2. Unhandled Exceptions Breaking User Assignment
Your current code uses get() calls without exception handling. If either MongoToken.objects.get() or User.objects.get() can’t find a matching record, it throws a DoesNotExist exception. This stops the middleware from completing, so request.user never gets set.
Even if your token is valid, issues like a missing HTTP_USERNAME header or a non-existent user would cause this. Let’s add error handling to catch these cases:
from models import MongoToken from django.contrib.auth.models import User from django.http import HttpResponseForbidden class TokenAuthenticationMiddleware(object): def process_request(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: return # Validate authorization header format try: tokenkey = auth_header.split()[1] except IndexError: return HttpResponseForbidden("Invalid authorization header format") # Fetch token with error handling try: token = MongoToken.objects.get(key=tokenkey) except MongoToken.DoesNotExist: return HttpResponseForbidden("Invalid token") # Fetch user from token (no need for HTTP_USERNAME) user = token.user if not user.is_active: return HttpResponseForbidden("User account is inactive") # Assign to request request.user = user request.token = tokenkey
3. Redundant (and Risky) User Fetch
You’re fetching the user twice: once via token.user (from the token’s relation) and once via HTTP_USERNAME. This is unnecessary and creates a security gap—an attacker could send a valid token paired with a different username to impersonate someone else.
Fix: Use the user directly linked to the token instead of relying on the HTTP_USERNAME header. This removes a potential point of failure and makes your auth flow more secure.
4. Unnecessary Token Key Check
Your condition token.key == tokenkey is redundant—since you fetched the token using key=tokenkey, this comparison will always be true. You can safely remove it to clean up your code.
内容的提问来源于stack exchange,提问作者MisterPy

