django rest框架TokenAuthentication无法正常工作

时间:2015-03-30 08:07:51

标签: python django django-rest-framework

想要使用令牌基础认证系统,所以api使用DRF调用获取列表,它总是抛出错误,我在本地系统中测试这个api。

"详细信息":"未提供身份验证凭据。"

Setting.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',

    ),       
}

Serializer.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,)

URL:

curl -H "Authorization: Bearer MDgYnKeoRsp0O4Hfgr9ka5tdfkKs6Y" http://127.0.0.1:8000/my/

错误:

{"detail":"Authentication credentials were not provided."}

1 个答案:

答案 0 :(得分: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