You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Remove redundant authentication and session login: The ObtainAuthToken serializer already handles validating username/password and authenticating the user. Your manual authenticate() call and login() are unnecessary and causing the session conflict.
  2. 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 ObtainAuthToken already uses Django’s authenticate() 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 csrftoken cookie from a previous request and include it in the X-CSRFToken header for subsequent POST requests. But for pure API token auth, this isn’t necessary.
  • Ensure your settings.py has TokenAuthentication enabled in REST_FRAMEWORK:
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.TokenAuthentication',
            # Other auth classes if needed
        ]
    }
    

内容的提问来源于stack exchange,提问作者Rashmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:03:19