Django 不识别我的令牌?

Django not recognizing my Token?

我在后端使用 Django Rest Framework,在前端使用 ember-cli 应用程序。身份验证工作正常,但授权中似乎存在漏洞。

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}

# views.py
class CurrentUserView(APIView):
    "get the data for the current authenticatd user"
    permission_classes = (IsAuthenticated,)

    def get_queryset(self, request):
        queryset = User.objects.filter(username=request.user.username)
        return queryset

    def get(self, request):
        serializer = UserSerializer(request.user)
        return Response(serializer.data)

当我向此端点发出请求时 /v1/me/ 它以 403 响应。当我取消权限 class 时,我返回 {"id":null,"username":"","is_active":false} 因为它没有知道我是谁。

此外,当我使用可浏览的 API 时,/v1/me URL 工作正常。

在 Ember 方面,我使用我的帐户登录并正确取回了我的令牌。在请求中,正在传递 Authorization: Token asdf1234asdf1234asdf1234。我会认为 Django 拿走了那个令牌并且知道我是谁?我错过了什么吗?

试试

from rest_framework import authentication
class TokenAuthView(APIView):
    authentication_classes = (authentication.TokenAuthentication,)

然后,

class CurrentUserView(TokenAuthView)

在设置中您需要添加auth_token。

# settings.py
   INSTALLED_APP = ('rest_framework.authtoken',)

您不需要在每个视图上添加 authentication_classes。