Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Authentication and Permissions in Django REST Framework

Introduction

Authentication and permissions are fundamental concepts in web development for securing APIs and ensuring that users have the appropriate access levels. Django REST Framework (DRF) provides robust mechanisms to handle authentication and permissions seamlessly.

Setting Up Django REST Framework

First, ensure you have Django and Django REST Framework installed. If not, you can install them using pip:

pip install django djangorestframework

Next, add 'rest_framework' to your Django project's INSTALLED_APPS in the settings.py file:

INSTALLED_APPS = [
    ...
    'rest_framework',
]
                

Basic Authentication

DRF supports multiple authentication methods out of the box. Basic Authentication is a simple authentication scheme built into the HTTP protocol where the client sends HTTP requests with the Authorization header that contains the word Basic followed by a space and a base64-encoded string username:password.

To enable Basic Authentication, update the DEFAULT_AUTHENTICATION_CLASSES in your settings.py file:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
    ],
}
                

Now, any API view will require authentication using Basic Authentication.

Token Authentication

Token Authentication is a more secure method and involves issuing a token to the user after they log in. This token is then used to authenticate subsequent requests.

First, install the Django REST Framework authtoken package:

pip install djangorestframework-authtoken

Add 'rest_framework.authtoken' to your INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'rest_framework.authtoken',
]
                

Run the migrations:

python manage.py migrate

Then, update your settings.py to include token authentication:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}
                

Create a view for obtaining the token:

from rest_framework.authtoken.views import obtain_auth_token
from django.urls import path

urlpatterns = [
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]
                

Users can now obtain a token by sending their username and password to /api-token-auth/.

Permissions

Permissions determine whether a request should be granted or denied access. DRF provides several built-in permissions, and you can also create custom permissions.

To set global permissions, update your settings.py:

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

This setting will ensure that all views require authenticated users.

Custom Permissions

Sometimes, the built-in permissions are not enough, and you need custom permissions. To create a custom permission, subclass BasePermission and override the has_permission or has_object_permission methods.

from rest_framework.permissions import BasePermission

class IsAdminUser(BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_staff
                

Apply this custom permission to a view:

from rest_framework.views import APIView
from rest_framework.response import Response
from .permissions import IsAdminUser

class MyAdminView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        return Response({"message": "Hello, Admin!"})
                

Conclusion

Authentication and permissions are critical for securing your APIs. Django REST Framework provides flexible and powerful tools to implement authentication and permissions in your applications. By understanding and using these tools, you can ensure that your APIs are secure and accessible only to authorized users.