django rest框架TokenAuthentication不起作用
Posted
技术标签:
【中文标题】django rest框架TokenAuthentication不起作用【英文标题】:django rest framework TokenAuthentication not working 【发布时间】:2015-03-30 08:07:50 【问题描述】:想要使用基于令牌的身份验证系统,所以 api 调用使用 DRF 获取列表,它总是抛出错误,我在本地系统中测试了这个 api。
"detail":"未提供身份验证凭据。"
设置.py
REST_FRAMEWORK =
'DEFAULT_AUTHENTICATION_CLASSES': (
#'rest_framework.permissions.IsAuthenticated',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
),
序列化器.py
class MyListSerializer(SignUpSerializer):
class Meta:
model = MyMod
fields = ('no', 'yes')
view.py
class MyList(generics.ListCreateAPIView):
queryset = MyMod.objects.all()
serializer_class = MyListSerializer
authentication_classes = (TokenAuthentication,)
网址:
curl -H "Authorization: Bearer MDgYnKeoRsp0O4Hfgr9ka5tdfkKs6Y" http://127.0.0.1:8000/my/
错误:
"detail":"Authentication credentials were not provided."
【问题讨论】:
你不是在混合 OAuth2Authentication 和 TokenAuthentication 吗?对于 TokenAuthentication,您应该使用此标头: Authorization: Token MDgYnKeoRsp0O4Hfgr9ka5tdfkKs6Y ("Token", not "Bearer") 感谢您的回复: curl -i -H "Authorization: Token MDgYnKeoRsp0O4Hfgr9ka5tdfkKs6Y" 127.0.0.1:8000/my 同样的错误 "detail":"Authentication credentials were not provided." @RaphaëlBraud 是在类视图中使用 TokenAuthentication 的正确方法。 使用 'Token' 前缀 Authorization 标头值是正确的方法,但你是如何得到 "MDgYnKeoRsp0O4Hfgr9ka5tdfkKs6Y" 的?你应该使用类似的东西: Token.objects.get_or_create(user=user).key 。是这样吗? 权限的主要问题 permission_classes = [TokenHasReadWriteScope] 而不是 authentication_classes = (TokenAuthentication,) 【参考方案1】:问题:
class MyList(generics.ListCreateAPIView):
queryset = MyMod.objects.all()
serializer_class = MyListSerializer
authentication_classes = (TokenAuthentication,)
解决方案:
class MyList(generics.ListCreateAPIView):
queryset = MyMod.objects.all()
serializer_class = MyListSerializer
permission_classes = [TokenHasReadWriteScope]
curl -H "授权:承载 MDgYnKeoRsp0O4Hfgr9ka5tdfkKs6Y" http://127.0.0.1:8000
【讨论】:
以上是关于django rest框架TokenAuthentication不起作用的主要内容,如果未能解决你的问题,请参考以下文章
带有 Django 2.0 的 Django REST 框架 URL
django.test.client 上的 Django rest 框架导入错误