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!
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.
Before diving into the authentication, make sure you have a basic understanding of:
To start, you need to add 'rest_framework' and 'rest_framework.authtoken' to your INSTALLED_APPS.
INSTALLED_APPS = [
# ...
'rest_framework',
'rest_framework.authtoken',
]In Django, users are managed by the built-in auth application. To create a user, run the following command:
python manage.py createsuperuserFollow the prompts to create your initial user account.
Let's create a simple view that requires authentication.
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.
DRF provides a built-in login view: django.contrib.auth.views.LoginView. To use it, add the following URL pattern to your urls.py.
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/.
Which URL pattern allows users to log in to our API?
Sometimes, you may need to authenticate users manually, for instance, in tests. Here's how to do it:
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.
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! π