Skip to main content
 首页 » 编程设计

python之使用 Postman 进行 Django Rest Framework token 身份验证

2024年12月31日22qlqwjy

我正在尝试使用 Postman 来测试我的 DRF 端点,但我总是收到 Authentication credentials were not provided. 错误。端点工作正常,但我还没有找到如何从 Postman 发送请求。

我能够为用户获取 token :

但是当我尝试使用 token 发送请求时,我总是得到错误:

我将授权类型设置为Inherit auth from parent。

这是 View 的代码:

class AlbumViewSet(viewsets.ModelViewSet): 
    permission_classes = (permissions.IsAuthenticated,) 
    queryset = proxies.AlbumProxy.objects.all() 
    serializer_class = serializers.AlbumSerializer 
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) 
    search_fields = ('name', 'description', 'company__name') 
    filter_fields = ('code', 'company') 
 
    def get_permissions(self): 
        if self.action == 'retrieve': 
            return [] 
 
        return super(AlbumViewSet, self).get_permissions() 
 
    def retrieve(self, request, pk): 
        password = request.query_params.get('password', None) 
 
        try: 
            instance = proxies.AlbumProxy.objects.get(pk=pk) 
        except: 
            return Response({'success': False, 'code': 1}) 
 
        if instance.access_code != password and password != settings.MASTER_KEY: 
            return Response({'success': False, 'code': 2}) 
 
        instance_to_return = serializers.AlbumSerializer(instance=instance, context={'request': request}).data 
        instance_to_return.pop('access_code') 
        instance_to_return['success'] = True 
 
        return Response(instance_to_return) 

这是我的 REST_FRAMEWORK 来自 settings 的常量:

REST_FRAMEWORK = { 
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 
    'DEFAULT_AUTHENTICATION_CLASSES': ( 
        'rest_framework.authentication.TokenAuthentication', 
        'rest_framework.authentication.SessionAuthentication', 
    ), 
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 
    'PAGE_SIZE': 20, 
    'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata' 
} 

请您参考如下方法:

就您使用 Apache 而言,您需要:

WSGIPassAuthorization On 

将它添加到您的 httpd.conf

更多详情 there .