Django REST framework – Setting permissions

Let’s continue our example in

 

So now we have a working endpoint @ http://127.0.0.1:8000/custom/get/.
django-rest-framework-permissions-1
 

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.
django-rest-framework-permissions-2
 

You will get the correct response only if u have logged in.
django-rest-framework-permissions-3
 

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.