Setting Up JWT Authentication in Django Rest Framework with Simple-JWT
JSON Web Tokens (JWT) offer a secure method for authenticating users in web applications. Using Simple-JWT with Django Rest Framework (DRF) is a popular approach to securing APIs. Below is a detailed guide to setting up JWT authentication in a Django project using Simple-JWT.
Step 1: Install Required Packages
First, install Django, Django Rest Framework, and Simple-JWT:
pip install django djangorestframework djangorestframework_simplejwt
Step 2: Create a Django Project
If you haven't already, start a new Django project:
django-admin startproject myproject
cd myproject
This command creates a new project structure like this:
myproject/
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
└── manage.py
Step 3: Create a Django App
Create a new app within your project:
python manage.py startapp myapp
Your project structure will now include:
myproject/
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
├── myapp/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations/
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── manage.py
Step 4: Configure Django Rest Framework
Add rest_framework
and rest_framework_simplejwt
to INSTALLED_APPS
in settings.py
:
INSTALLED_APPS = [
# Default apps
'rest_framework',
'rest_framework_simplejwt',
'myapp', # Replace 'myapp' with your app's name
]
Step 5: Configure JWT Settings
Configure JWT authentication in settings.py
:
from datetime import timedelta
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
# Adjust token lifetimes as needed
}
Step 6: Define Token Endpoints
Include Simple-JWT endpoints in your project's urls.py
:
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('', include('myapp.urls')), # Include your app's URLs
]
Step 7: Create API Views
Define API views in myapp/views.py
. These endpoints require authentication:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class Home(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'message': 'Hello, World!'})
Step 8: Configure App URLs
Create myapp/urls.py
and define your app's URLs:
from django.urls import path
from .views import Home
urlpatterns = [
path('', Home.as_view()),
]
Step 9: Run Migrations
Apply database migrations:
python manage.py migrate
Step 10: Test Your Setup
Create a superuser to test your application:
python manage.py createsuperuser
Run the development server:
python manage.py runserver
Use a tool like Postman to test your API endpoints. Obtain an access token by making a POST request to http://127.0.0.1:8000/api/token/
with valid user credentials. Use the access token as a Bearer Token to access authenticated endpoints like
http://127.0.0.1:8000/
.
Conclusion
You've successfully set up JWT authentication in Django Rest Framework using Simple-JWT. This setup provides a robust and secure way to authenticate users and control access to protected resources in your Django application. Ensure your client application handles token expiration and refreshing appropriately for a seamless user experience.