【问题标题】:Django Rest: Why is the access denied, although AccessAny is set as permission?Django Rest:为什么访问被拒绝,尽管 AccessAny 被设置为权限?
【发布时间】:2021-10-02 19:10:23
【问题描述】:

我想向所有人授予对我的 API 没有任何权限的访问权限。我在文件中做了以下定义:

views.py

from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from rest_framework.permissions import AllowAny
from django.http import HttpResponse, JsonResponse
from rest_framework import status
from api.models import Application, Indice, Satellite, Band
from api.serializers import OsdSerializer
import logging
logger = logging.getLogger(__name__)

class OsdView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        applications = Application.objects.all()
        serializer = OsdSerializer(applications, many=True)
        return Response({"Applications:": serializer.data})

class DetailView(APIView):
    permission_classes = [AllowAny]

    def get(self, request, machine_name):
        application = Application.objects.get(machine_name=machine_name)
        downloads = OsdSerializer(application, context={"date_from": request.query_params.get("from", None), "date_to": request.query_params.get("to", None), "location": request.query_params.get("location", None), })

        return Response(downloads.data)

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}

但是当我访问 API 时,结果如下而不是内容:

{"detail":"Invalid username/password."}

【问题讨论】:

  • 这是因为身份验证而不是权限。看看你的身份验证是否正确

标签: django rest django-rest-framework permissions


【解决方案1】:

您还必须添加身份验证:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
    ],

}

这就是您收到错误的原因;不用担心,即使没有(至少是 GET!)登录,任何人都会看到您的 API 数据。

【讨论】:

  • 谢谢,不知道权限和身份验证类之间有区别。您的评论很有帮助?
猜你喜欢
  • 2019-06-15
  • 2022-01-02
  • 2014-08-10
  • 2014-01-27
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多