Django无法处理多用户登录问题求助
Fixing Multi-User Login CSRF Error in Django Token Authentication
The root cause of your issue is that you’re calling login(request, valid_user) in your CustomAuthToken view. This initiates session-based authentication alongside your token-based setup, triggering Django’s CSRF protection for subsequent requests. Once a session is created for the first user, Django expects a CSRF token in any follow-up POST requests (like logging in another user)—which Postman isn’t providing, hence the "CSRF Failed" error.
Step-by-Step Fix
- Remove redundant authentication and session login: The
ObtainAuthTokenserializer already handles validating username/password and authenticating the user. Your manualauthenticate()call andlogin()are unnecessary and causing the session conflict. - Simplify your view to rely on the serializer’s built-in validation:
Corrected Code
from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.response import Response from rest_framework.authtoken.models import Token class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): # Let the serializer handle username/password validation and authentication serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email })
Why This Works
- By removing
login(), you avoid creating a persistent session for the authenticated user. Token authentication is stateless, so each login request is independent—no session cookies are set, and Django won’t enforce CSRF checks for these requests. - The serializer from
ObtainAuthTokenalready uses Django’sauthenticate()under the hood to validate credentials, so you don’t need to call it manually.
Additional Notes
- If you need both session-based auth (for web views) and token-based auth (for APIs), you’ll need to handle CSRF tokens in Postman: retrieve the
csrftokencookie from a previous request and include it in theX-CSRFTokenheader for subsequent POST requests. But for pure API token auth, this isn’t necessary. - Ensure your
settings.pyhasTokenAuthenticationenabled inREST_FRAMEWORK:REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # Other auth classes if needed ] }
内容的提问来源于stack exchange,提问作者Rashmi
相关产品推荐
相关产品推荐

