RESTful APIs / RESTful APIs with Django and Django REST Framework

Handling Authentication and Permissions

This tutorial will guide you through the process of implementing authentication and permissions in Django REST Framework. You'll learn how to protect your API's endpoints and mana…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers building RESTful APIs using Django and Django REST Framework.

1. Introduction

1.1 Goal of the Tutorial

This tutorial aims to guide you through the process of implementing authentication and permissions in Django REST Framework. By the end of the tutorial, you will be able to protect your API's endpoints and manage user permissions effectively.

1.2 Learning Outcomes

  • Understand the concept of authentication and permissions in Django REST Framework
  • Learn to implement token-based authentication
  • Learn to manage user permissions and protect API endpoints

1.3 Prerequisites

  • Basic knowledge of Python
  • Familiarity with Django and Django REST Framework

2. Step-by-Step Guide

2.1 Authentication

Authentication is the process of verifying a user's identity. In Django REST Framework, there are various methods of authentication like Basic Authentication, Token Authentication, and Session Authentication. In this tutorial, we will focus on Token Authentication.

2.2 Permissions

Permissions determine whether a request should be granted or denied access. Django REST Framework provides a set of predefined permissions like IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly. You can also create custom permissions.

3. Code Examples

3.1 Implementing Token Authentication

First, you need to include the rest_framework.authtoken in your INSTALLED_APPS:

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

Then, to set Token Authentication as your default authentication scheme, update the REST_FRAMEWORK setting in your Django settings.py:

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

When a user successfully logs in, you can create a token for them:

from rest_framework.authtoken.models import Token

def login(request):
    # authentication logic here
    token = Token.objects.create(user=...)
    return Response({'token': token.key})

The client must include the token in the Authorization HTTP header for every request:

```http request
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b


## 3.2 Managing User Permissions
To require that a user is authenticated to view an API endpoint, you can use `IsAuthenticated` permission. Add the `permission_classes` attribute to your view:

```python
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

If a request from an unauthenticated user hits this endpoint, a 401 Unauthorized response will be returned.

4. Summary

In this tutorial, we have discussed:
- What authentication and permissions are in the context of Django REST Framework
- How to implement Token Authentication
- How to manage user permissions using predefined permission classes

To further your understanding, you might want to explore other authentication methods and how to create custom permissions.

5. Practice Exercises

  1. Implement a custom permission that allows access to a view only to users with a username that starts with 'A'.
  2. Implement a view that uses both Token Authentication and your custom permission from exercise 1. Test it with different users.

5.1 Exercise Solutions

  1. Custom Permission:
from rest_framework import permissions

class IsNameStartsWithA(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user.username.startswith('A')
  1. View with Token Authentication and custom permission:
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class CustomView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated, IsNameStartsWithA]

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

Test this view with different users. Only users with a token and a username that starts with 'A' should be able to access it.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Watermark Generator

Add watermarks to images easily.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help