我正在关注this检查 api_key
header 是否存在的教程。该示例似乎用于身份验证目的,我无法弄清楚如何修复它。当我访问 API 端点时,出现错误:
{
"detail": "You do not have permission to perform this action."
}
permisson.py
从rest_framework.permissions导入BasePermission
class Check_API_KEY_Auth(BasePermission):
def has_permission(self, request, view):
# API_KEY should be in request headers to authenticate requests
api_key_secret = request.META.get('API_KEY')
if 'api_key' in request.headers:
api_key_secret = request.headers['api_key']
if api_key_secret == 'adnan':
print('FOUND')
return api_key_secret == 'you'
views.py
from rest_framework import viewsets
from .models import App
from .serializers import AppSerializer
from rest_framework.decorators import action
from rest_framework.response import Response
from .permissions import Check_API_KEY_Auth
class AppView(viewsets.ModelViewSet):
queryset = App.objects.all()
permission_classes = (Check_API_KEY_Auth,)
serializer_class = AppSerializer
def show(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
我不需要用户身份验证,我只需要检查 API_KEY 是否存在,如果存在则查询表中的数据库并返回结果。
最佳答案
如果permission_classes
中的所有权限返回True
,则django-rest-framework
授予权限,如果列表中的任何一个返回False
则权限被拒绝
查看 Check_API_KEY_Auth
类后,返回 True
的唯一情况是 URL 中存在 API_KEY=you
,否则它将始终返回 False
,这就是为什么当 URL 中没有 API_KEY
时,它会给出此错误消息。
教程中的那个是最短的,它将 api_key_secret == settings.API_KEY_SECRET
的输出直接返回到 View ,该 View 仅产生 True
或 假
关于python - Django Rest Framework 给出错误 : You do not have permission to perform this action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65020725/