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

请求协助:Authentication Token无法正常传递问题排查

排查Authentication Token传递失败的问题

先看你代码里最致命的问题:

  • test_notify_api_success方法没有缩进,不属于NotifyViewTests类。这会导致方法里的self.client、self.user、self.token都无法正确引用类实例属性,直接触发错误,更别说Token正常传递了。先把这个方法缩进,放到类内部。

接下来逐个排查其他可能的问题:

1. force_authenticate参数使用错误

DRF的force_authenticate方法中,token参数需要传递Token对象,而非token的key字符串。你当前传的是self.token.key(字符串),应该改成:

self.client.force_authenticate(user=self.user, token=self.token)

或者也可以直接给请求头添加Token认证信息:

self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)

2. 检查User模型字段是否合法

默认Django的User模型没有name字段,只有username。你用User.objects.create_user时传了name='test',如果没自定义User模型,这会抛出参数错误。如果是自定义模型,确保create_user方法支持name参数;如果用默认模型,把name改成username:

self.user = User.objects.create_user(
    username='test',            
    email='tes111t@test.com',
    password='test123',
)

3. 确认视图类的认证配置

检查你的NotifyView是否配置了TokenAuthentication:

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

class NotifyView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    
    # 其他视图逻辑...

如果视图没配置Token认证,就算传递了Token也不会生效。

4. 打印响应内容定位具体错误

在断言前打印响应数据,能直观看到错误原因:

response = self.client.post(url, data, format='json')
print(response.data)  # 打印响应内容,明确错误类型
self.assertEqual(response.status_code, status.HTTP_201_CREATED)

比如认证失败时,响应会返回类似{"detail": "Authentication credentials were not provided."}的信息,帮你快速定位问题。

先修复缩进问题,再逐个排查上述点,基本就能解决Token传递异常的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:20:26