Django REST Framework (DRF) Authentication Tutorial 🎯

beginner
8 min

Django REST Framework (DRF) Authentication Tutorial 🎯

Welcome to our in-depth guide on Authentication in Django REST Framework (DRF)! In this lesson, we'll learn how to secure your APIs using Django's built-in authentication system. This tutorial is designed for beginners and intermediates, so let's get started!

Introduction πŸ“

DRF provides a powerful and flexible way to build APIs in Django. However, it's crucial to secure these APIs against unauthorized access. In this lesson, we'll focus on two main authentication classes: django.contrib.auth.views.LoginView and rest_framework.authentication.SessionAuthentication.

Prerequisites βœ…

Before diving into the authentication, make sure you have a basic understanding of:

  1. Django: Django Tutorial
  2. Django REST Framework: Django REST Framework Tutorial

Setting Up Authentication πŸ’‘

To start, you need to add 'rest_framework' and 'rest_framework.authtoken' to your INSTALLED_APPS.

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

Creating a User πŸ“

In Django, users are managed by the built-in auth application. To create a user, run the following command:

bash
python manage.py createsuperuser

Follow the prompts to create your initial user account.

Basic Authentication Using Session πŸ’‘

Let's create a simple view that requires authentication.

python
from rest_framework import generics from .models import MyModel class MyModelList(generics.ListCreateAPIView): queryset = MyModel.objects.all() permission_classes = [permissions.IsAuthenticated]

Now, only authenticated users can access this view. However, you might be wondering, "How do users log in?" Let's create a login view for that.

Creating a Login View πŸ’‘

DRF provides a built-in login view: django.contrib.auth.views.LoginView. To use it, add the following URL pattern to your urls.py.

python
from django.urls import path from django.contrib.auth.views import LoginView urlpatterns = [ # ... path('login/', LoginView.as_view(), name='login'), ]

Now, you can access the login view at /login/.

Quick Quiz
Question 1 of 1

Which URL pattern allows users to log in to our API?

Authenticating Users Manually πŸ’‘

Sometimes, you may need to authenticate users manually, for instance, in tests. Here's how to do it:

python
from rest_framework.authentication import SessionAuthentication from rest_framework.authtoken.models import Token from django.contrib.auth import get_user_model User = get_user_model() user = User.objects.get(username='myusername') token, created = Token.objects.get_or_create(user=user) request.user = user request.META['HTTP_AUTHORIZATION'] = f'Token {token}'

In this code, we create a user token for our user, set the user on the request object, and add the token to the HTTP authorization header.

Advanced Authentication Using JWT πŸ’‘

For more robust security, consider using JSON Web Tokens (JWT) for authentication. To set this up, follow the JWT Authentication in DRF tutorial.


Stay tuned for more Django and Django REST Framework tutorials! Don't forget to practice by creating your own authenticated APIs. Happy coding! πŸŽ‰