【问题标题】:Django rest framework Authentication not recognizing UserDjango rest框架身份验证无法识别用户
【发布时间】:2021-07-08 09:01:53
【问题描述】:

当我使用“IsAdminUser”或“IsAuthenticated”时,我无法再访问 api 视图并显示“详细信息”:“未提供身份验证凭据。”

当我将其设置为“AllowAny”或根本不设置身份验证时,它可以正常工作。

Views.py

from rest_framework import generics, status, permissions
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAdminUser

class CreatePost(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAdminUser,)
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request, format=None):
        print(request.data)
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Settings.py

INSTALLED_APPS = [
    'rest_framework.authtoken',
    'rest_framework',
    'rest_auth',
    'corsheaders',

    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    'allauth.socialaccount',

    'news.apps.NewsConfig',
    'api.apps.ApiConfig'
]


REST_FRAMEWORK = {
    
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),

    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
}

【问题讨论】:

  • 您未在请求中提供身份验证信息。包括您正在执行的请求
  • 我不明白

标签: django-rest-framework


【解决方案1】:

您必须在标头中提供身份验证详细信息,因为您已在 DEFAULT_AUTHENTICATION_CLASSES 中激活 TokenAuthentication,正如响应告诉您的那样。 这意味着您应该使用令牌向您的请求添加授权标头,您必须为每个用户创建该令牌。 例如使用 curl 发送请求:

curl --request POST '127.0.0.1:8000/yourendpoint/'
--header 'Authorization: c2vU15dD.kurnNras5GFM7oP0jsv4Bdasdsadas'

在这里阅读更多: https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

DRF 中的默认令牌认证方案非常简单,您应该考虑像 Djoser 这样的包。如果没有,请阅读链接中的说明,一切顺利。

如果这对您有帮助,请在左侧将其标记为答案。

【讨论】:

    猜你喜欢
    • 2013-06-29
    • 2017-09-26
    • 2017-11-02
    • 2018-02-12
    • 2021-06-05
    • 1970-01-01
    • 2019-03-01
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多