How to Configure JWT Authentication in Django
JSON Web Tokens (JWT) have become a popular method for securing APIs and authenticating users in modern web applications. Django, combined with the Django REST Framework (DRF), provides a robust platform to implement JWT authentication efficiently. This tutorial will guide you step-by-step on how to configure JWT authentication in your Django project.
Prerequisites
- Basic knowledge of Python and Django.
- Django project with Django REST Framework installed.
- Python 3.6 or newer.
- Familiarity with REST APIs.
Step 1: Setting Up Your Django Project with DRF
If you do not already have Django and Django REST Framework installed, start by installing them:
pip install django djangorestframework
Create a new Django project if you haven’t done so:
django-admin startproject myproject
cd myproject
Then create an app (optional but recommended for better structure):
python manage.py startapp api
Add rest_framework and your app to the INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
# default apps...
'rest_framework',
'api',
]
Step 2: Installing JWT Authentication Package
We will use djangorestframework-simplejwt (Official site), a popular package for JWT authentication with DRF.
Install it using pip:
pip install djangorestframework-simplejwt
Step 3: Configuring Django REST Framework to Use JWT
Edit your settings.py to configure DRF authentication classes to include JWT authentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
Step 4: Adding JWT Views to Your URLs
You need to provide endpoints for obtaining and refreshing tokens. Edit your urls.py to include these:
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
Step 5: Protecting Your Views with JWT Authentication
For demonstration, let’s create a simple protected API view in your api/views.py:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class HelloWorldView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request):
return Response({'message': 'Hello, authenticated user!'})
Now add this view to your app’s urls.py:
from django.urls import path
from .views import HelloWorldView
urlpatterns = [
path('hello/', HelloWorldView.as_view(), name='hello_world'),
]
Make sure to include your app urls in the main urls.py too:
path('api/', include('api.urls'))
Step 6: Testing JWT Authentication
Run your server:
python manage.py runserver
Use a tool like Postman or curl to test your endpoints:
- Request a token with your user credentials to
/api/token/. - Use the received access token in the Authorization header as
Bearer YOUR_TOKEN_HEREto access protected views like/api/hello/. - Refresh tokens using
/api/token/refresh/endpoint.
Troubleshooting
- Invalid token or authentication failed: Ensure the token is sent in the header correctly as
Authorization: Bearer <token>. - Package not found or import errors: Confirm you installed
djangorestframework-simplejwtand it’s included in your environment. - Permission Denied: Check that your view has the appropriate permission classes and user is authenticated.
Summary Checklist
- Install Django, Django REST Framework, and djangorestframework-simplejwt.
- Configure
settings.pyREST_FRAMEWORK authentication classes. - Add token obtain and refresh views to
urls.py. - Create protected API views with
IsAuthenticatedpermission. - Test token generation, usage, and refreshing.
For further advanced configuration, such as customizing token claims, expiration times, or adding blacklisting, refer to the official Simple JWT documentation.
Also, check our related tutorial on building REST APIs with Django for a broader understanding of API development.
