Handling Authentication and Permissions

Tutorial 3 of 5

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.