Reputation: 15008
I am following this tutorial to check whether api_key
header exist or not. The example seems for authentication purpose and I am unable to figure out how to fix it. When I access the API endpoint I get an error:
{
"detail": "You do not have permission to perform this action."
}
permisson.py
from rest_framework.permissions import 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)
I do not need user auth, all I ned to check API_KEY exist or not, if yes then query against db in a table and return results.
Upvotes: 2
Views: 5279
Reputation: 1330
A permission is granted by django-rest-framework
if all permissions in permission_classes
return True
, if any one in the list return False
then permission is denied
After looking at Check_API_KEY_Auth
class the only case when this will return True
is when API_KEY=you
in the URL, otherwise it will always return False
and that's why when there is no API_KEY
in URL it gives this error msg.
The one in the tutorial is the shortest one, it returns the output of api_key_secret == settings.API_KEY_SECRET
directly to the view which is only yields to True
or False
Upvotes: 2