首页 > 解决方案 > "detail": "未提供身份验证凭据。"

问题描述

``我正在尝试在我的 Django Rest Framework 应用程序中实现令牌身份验证。我能够从 django 服务器接收令牌,但是当我发送带有“授权”标头的请求时,我收到以下错误:

{ "detail": "未提供身份验证凭据。" }

我还检查了 request.META 并且没有名称为“HTTP_AUTHORIZATION”的键。我在开发服务器上运行我的 django 应用程序。

视图.py

# Create your views here.
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view,authentication_classes,permission_classes
from django.contrib.auth.decorators import permission_required,login_required
import google.cloud.storage
import uuid
import psycopg2


@api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication))
@permission_classes((IsAuthenticated,))
def auth_test(request):
    return Response("it's great to have you here with token auth!!")

@api_view(['GET'])
def free_test(request):
    #print(request.META['HTTP_AUTHORIZATION'])
    return Response("entry without token auth !!")

django 服务器未收到我的授权凭据的原因是什么?

邮递员屏幕截图,我通过了授权标题

截屏

标签: authenticationdjango-rest-frameworkpostman

解决方案


您正在尝试使用Tokenauth 方法访问您的视图,但在authentication_classes. 试试下面的代码


from rest_framework.authentication import TokenAuthentication


@api_view(['GET'])
@authentication_classes((SessionAuthentication, TokenAuthentication, BasicAuthentication))
@permission_classes((IsAuthenticated,))
def auth_test(request):
    return Response("it's great to have you here with token auth!!")


推荐阅读