无法使用邮递员和授权令牌访问后端

时间:2020-02-04 05:22:17

标签: django angular jwt jwt-auth

Angular 8和Django3。我正在使用自定义视图类user_id从Django获取tokenCustomAuthToken。我收到一个包含tokenuser_id的响应。我正在学习一个教程,并想测试将自定义标头发送到django以查看授权是否可行。

我正在使用邮递员,并将标头设置为Authorization: Bearer 1a683...9e428。当我向http://127.0.0.1:8000/users/dashboard/23发送GET请求时,得到响应 "detail": "Authentication credentials were not provided."

我的理解是提供这些标题应该起作用吗?还是客户端上有一些东西可以解码头并将其发送回去?

views.py

class CustomAuthToken(ObtainAuthToken):

    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,
            'user_id': user.pk,
        })

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',

    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),

}

urls.py

urlpatterns = [
    path('dashboard/<int:pk>', UserDashboard.as_view(), name='dashboard'),
    path(r'api-token-auth/', CustomAuthToken.as_view()),
    ]

1 个答案:

答案 0 :(得分:0)

授权标头中的前缀应为Token而不是承载符:

Authorization: Token 1a683...9e428

有关更多详细信息,请参见docs