How to Set Up Token Authentication in Django Rest Framework in 2023?

In today’s ever-evolving world of building websites and online applications, ensuring your software is safe and protected is essential. That’s where token authentication comes in – it’s a crucial technique for securing your Django REST Framework (DRF) APIs. Think of token authentication as a smart and reliable method to create a safe connection between the people using your app and the servers that run it. This clever approach helps you avoid the risks of sharing sensitive login details.
In this blog post, we’ll guide you through the process of seamlessly integrating token authentication into your DRF project. We’ll start with the basic setup and then show you exactly how this security measure works in the real world. By the end of this post, you’ll not only know ‘how’ to do it, but also ‘why’ it’s so important. So, get ready to improve your app’s security while learning something new along the way!
Token authentication might sound fancy, but it’s really just a way to keep your app’s data safe and sound. You’re in the right place if you’re using the Django REST Framework (DRF). In this blog post, we’re going to take you through the process of setting up token authentication for your DRF project, step by step. Don’t worry – we’ll explain everything without the technical jargon. We’ll show you how to make your app more secure and explain why it matters. So, get ready to dive in and make your app safer.
Requirements
We need the following packages to be in your system for Token authentication:
- Python
- Django
- Django REST Framework
Installing Django
pip install django
Installing the Django REST Framework:
pip install djangorestframework
Step 1: Create a Django Project and App
First, let’s create a new Django project and an app within it:
$ django-admin startproject project_name
$ cd project_name
$ python manage.py startapp api_app
Step 2: Configure Settings
In the settings.py file of your project, add the following configurations:
INSTALLED_APPS = [
# ...
'rest_framework',
'rest_framework.authtoken',
'api_app',
# ...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
# ...
}
Step 3: Create Models and Migrations
Define the models you want to expose through your API in the models.py file of your api_app. After defining the models, create migrations and apply them:
$ python manage.py makemigrations
$ python manage.py migrate
Step 4: Create Serializers
Create serializers in the serializers.py file of your api_app to convert model instances to JSON data:
from rest_framework import serializers
from .models import YourModel
class YourModelSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = '__all__'
Step 5: Create Views
In the views.py file of your api_app, create views using DRF’s viewsets:
python
Copy code
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated # Import the IsAuthenticated permission
from .models import YourModel
from .serializers import YourModelSerializer
class YourModelViewSet(viewsets.ModelViewSet):
queryset = YourModel.objects.all()
serializer_class = YourModelSerializer
permission_classes = [IsAuthenticated]
Step 6: Configure URLs
Define the URLs for your API endpoints in the urls.py file of your api_app:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import YourModelViewSet
router = DefaultRouter()
router.register(r'your-model', YourModelViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Step 7: Create Superuser and Run Server
Create a superuser to access the Django admin panel and run the development server:
$python manage.py createsuperuser
$ python manage.py runserver
Step 8: Obtain and Use Tokens
Go to http://localhost:8000/admin/ and log in with the superuser credentials.
Navigate to “Token” under the “Authentication and Authorization” section.
Create a token for your user.
Access Protected Views using the Token:
To access the views that are protected by token authentication, you need to include the token in the Authorization header of your HTTP requests. Here’s how you can do it:
import requests
url = 'http://localhost:8000/api/your-endpoint/' # Replace with the actual API endpoint URL
token = 'your-token-key' # Replace with the actual token key
headers = {
'Authorization': f'Token {token}'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f"Request failed with status code: {response.status_code}")
Replace ‘your-token-key’ with the actual token key you obtained from the Django admin panel. Also, replace ‘http://localhost:8000/api/your-endpoint/’ with the URL of the protected API endpoint you want to access.
This code snippet demonstrates how to make a GET request to an API endpoint using the token as part of the Authorization header. You can adapt this code for other types of requests like POST, PUT, DELETE, etc.
Response
If the token is not valid or has expired, the server will typically respond with a 401 Unauthorized status code.
If the token is valid, user can use the view, and it’s functionality
Create a Class-Based View for Token Generation:
In myapp/views.py, create a class-based view that generates an access token for a given user:
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class GetAccessTokenView(APIView):
permission_classes = [IsAuthenticated] # Only allow authenticated users to request tokens
def post(self, request, *args, **kwargs):
user = request.user
token, created = Token.objects.get_or_create(user=user)
return Response({'access_token': token.key})
Configure URL Routing:
In myapp/urls.py, configure the URL routing to map the class-based view:
from django.urls import path
from .views import GetAccessTokenView
urlpatterns = [
path('get-access-token/', GetAccessTokenView.as_view(), name='get-access-token'),
# Add other URLs as needed
]
Access the Token URL:
Similar to the previous example, an authenticated user can access the /get-access-token/ URL to request their access token:
curl -H "Authorization: Token your-user-token" http://localhost:8000/api/get-access-token/
Replace your-user-token with the actual token of the user making the request.
To read more about Throttling in Django Rest Framework, refer to our blog How to Master Throttling in Django Rest Framework
Conclusion
From the very start of setting up your project, all the way to the exciting moment of accessing those well-protected views, we’ve guided you through every key step. As you’ve become familiar with the details of models, serializers, and views, you’ve gained the power to smoothly put token authentication into action. Now that you have this fresh knowledge in your toolkit, you’re fully prepared to create access tokens for users and use them like keys to open the doors to your secure API zones.