Django REST+Vuejs调用obtain_auth_token时CSRF禁用仍报错
问题分析与解决方案
核心原因:DRF SessionAuthentication的独立CSRF检查
你使用了Django原生的csrf_exempt装饰器,但DRF的SessionAuthentication自身带有独立的CSRF验证逻辑,原生装饰器无法绕过DRF内部的这层检查。再加上全局配置中DEFAULT_AUTHENTICATION_CLASSES包含SessionAuthentication,导致即使接口加了Django的csrf_exempt,POST请求依然会触发DRF的CSRF校验。
解决方案1:替换为DRF专属的csrf_exempt装饰器
将urls.py中的导入替换为DRF提供的csrf_exempt,它能同时绕过Django的CsrfViewMiddleware和DRF SessionAuthentication的CSRF检查:
from rest_framework.decorators import csrf_exempt # 替换Django原生的csrf_exempt from rest_framework.authtoken.views import obtain_auth_token path("api/auth-token/", csrf_exempt(obtain_auth_token)),
解决方案2:自定义认证视图,移除SessionAuthentication
创建一个自定义的ObtainAuthToken视图,仅保留TokenAuthentication,从根源避免CSRF校验触发:
# 在项目的views.py中添加 from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny class CustomAuthToken(ObtainAuthToken): # 仅启用Token认证,剔除SessionAuthentication authentication_classes = [TokenAuthentication] # 允许匿名访问该接口(覆盖全局的IsAuthenticated权限配置) permission_classes = [AllowAny] def post(self, request, *args, **kwargs): 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})
然后在urls.py中替换原有路由:
from .views import CustomAuthToken path("api/auth-token/", CustomAuthToken.as_view()),
额外检查项
- 确认生产环境Traefik配置未修改或过滤
Content-Type等请求头,确保POST的JSON数据能被后端正常解析。 - 核对生产环境路由配置与测试环境一致,避免出现路由覆盖或映射错误。
内容的提问来源于stack exchange,提问作者joe
相关产品推荐
相关产品推荐

