Let’s continue our example in
So now we have a working endpoint @ http://127.0.0.1:8000/custom/get/.
Now we would like to add authentication on this endpoint and return 403 if the request is not authorized.
First, if you want to set the authentication globally, you could set it in the settings.py.
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) }
Restart the application and try to access the endpoint again. You will get a 403.
You will get the correct response only if u have logged in.
Similarly, you need to provide the user credential when using the curl command.
curl -u <username>:<password> http://127.0.0.1:8000/custom/get/
But sometimes, we only want to add the authentication to some specific endpoint. In that case, you don’t need to alter the global config in settings.py. Instead, add the permission_classes in the views.py as follow.
<django_root>/custom/views.py
from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response from statsd.defaults.django import statsd class CustomGet(APIView): """ A custom endpoint for GET request. """ permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): """ Return a hardcoded response. """ return Response({"success": True, "content": "Hello World!"})
Done =)
Reference: Django REST framework – Permissions