Setting Up Token Authentication with Django Rest Framework

Diwakar Rankawat
2 min readJan 28, 2024

--

Photo by Fahim Muntashir on Unsplash

Introduction

Token authentication is a straightforward and effective way to handle user authentication in web applications. In this post, we’ll go through how to set up token authentication using Django Rest Framework (DRF).

Prerequisites

  • Basic knowledge of Python and Django.
  • Django and Django Rest Framework installed in your environment.

1. Adding DRF and Token Authentication

  • Install DRF: If not already installed, add it via pip:
pip install djangorestframework
  • Update Installed Apps: In your Django settings.py, add rest_framework and rest_framework.authtoken:
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
]
  • Configure DRF: In settings.py, add the following to set up token authentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
  • Database Migration: Run python manage.py migrate to update the database with the new authentication model.

2. Creating an API for Token Generation

  • User Serializer: In serializers.py, define a serializer for user registration:
from django.contrib.auth.models import User
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'password']
extra_kwargs = {'password': {'write_only': True}}
  • User Registration View: In views.py, create a view to handle user registration and token generation:
from rest_framework.authtoken.models import Token
from rest_framework import generics
from .serializers import UserSerializer

class CreateUserView(generics.CreateAPIView):
serializer_class = UserSerializer

def perform_create(self, serializer):
user = serializer.save()
Token.objects.create(user=user)
  • URL Configuration: In urls.py, add a URL for the registration view:
from django.urls import path
from .views import CreateUserView

urlpatterns = [
path('register/', CreateUserView.as_view(), name='register'),
]

3. Creating an Authenticated API View

  • Protected API View: In views.py, create a view that requires authentication:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

class HelloView(APIView):
permission_classes = [IsAuthenticated]

def get(self, request):
return Response({'message': 'Hello, Authenticated User!'})
  • URL for Authenticated View: Add this view to urls.py:
path('hello/', HelloView.as_view(), name='hello'),

4. Headers for Token Authentication

When making requests to authenticated endpoints, include the token in the request header.

Example using cURL:

curl -X GET http://127.0.0.1:8000/hello/ \
-H "Authorization: Token your_token_here"

Example using Python Requests:

import requests
headers = {'Authorization': 'Token your_token_here'}
response = requests.get("http://127.0.0.1:8000/hello/", headers=headers)
print(response.json())

Conclusion

Setting up token authentication with Django Rest Framework is a straightforward process that enhances the security of your application. By following these steps, you can ensure that only authenticated users access certain endpoints in your application.

--

--

No responses yet