Secure Token Creation in Django with djangorestframework-simplejwt
Last updated 4 months ago | 326 views 75 5

Introduction: Why JWT Token Creation Matters in Django
In the age of mobile-first development and modern frontend frameworks like React and Vue, stateless APIs are essential. Traditional session-based authentication often falls short in cross-platform applications.
That’s where JWT (JSON Web Tokens) shine.
djangorestframework-simplejwt is a robust package built for Django REST Framework that helps you implement token-based authentication using JWTs. This allows your API to be stateless, scalable, and secure — making it ideal for single-page apps (SPAs), mobile apps, and microservices.
In this guide, we’ll walk through how to create, use, and manage tokens using SimpleJWT in Django.
Step-by-Step: Implementing Token Creation with SimpleJWT
✅ Step 1: Install Required Packages
pip install djangorestframework djangorestframework-simplejwt
✅ Step 2: Add to Installed Apps
In settings.py
:
INSTALLED_APPS = [
...,
'rest_framework',
'rest_framework_simplejwt',
]
✅ Step 3: Configure REST Framework Authentication
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
✅ Step 4: Set Up Token URLs
In your main or app-level urls.py
:
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView, # Login endpoint
TokenRefreshView, # To refresh token
TokenVerifyView # Optional: verify token validity
)
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]
✅ Step 5: Test Token Creation
Use Postman or cURL to test:
POST /api/token/
Body:
{
"username": "your_username",
"password": "your_password"
}
Response:
{
"refresh": "long-refresh-token-here",
"access": "short-access-token-here"
}
Use the access token in headers like this:
Authorization: Bearer your-access-token
✅ Step 6: Protect Views with Token Auth
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class HelloTokenUser(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({"message": f"Hello, {request.user.username}!"})
What Are Access and Refresh Tokens?
Token Type | Purpose | Default Expiry |
---|---|---|
Access Token | Used for authenticating requests | 5 minutes |
Refresh Token | Used to obtain new access tokens | 1 day |
You can customize token lifetime in settings.py
:
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
}
Full Working Example: Token Creation in Django
settings.py
INSTALLED_APPS = [
'rest_framework',
'rest_framework_simplejwt',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
}
urls.py
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from .views import HelloTokenUser
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/hello/', HelloTokenUser.as_view(), name='hello_token_user'),
]
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class HelloTokenUser(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({"message": f"Hello, {request.user.username}!"})
Tips & Common Pitfalls
✅ Best Practices
-
Use HTTPS to prevent token sniffing.
-
Keep access tokens short-lived and refresh tokens secure.
-
Implement token blacklisting if users log out or reset passwords.
-
Use TokenVerifyView to check token validity for debugging.
❌ Common Pitfalls
-
Forgetting
Bearer
prefix in the Authorization header. -
Using expired access tokens without refreshing.
-
Misconfiguring
DEFAULT_AUTHENTICATION_CLASSES
. -
Not rotating tokens for long sessions.
JWT vs DRF TokenAuth (Comparison)
Feature | DRF TokenAuth | SimpleJWT (JWT) |
---|---|---|
Token Expiry | No | Yes (configurable) |
Stateless | Partially | Fully Stateless |
Refresh Support | Manual | Built-in |
Mobile App Friendly | Moderate | Excellent |
Ideal Use Case | Quick Auth Setup | Scalable APIs |
✅ Conclusion: Build Secure and Scalable APIs with JWT
Token creation using djangorestframework-simplejwt
provides a scalable, secure, and flexible authentication mechanism for your Django APIs.
Key Takeaways
-
Use
TokenObtainPairView
for login and token generation. -
Add
JWTAuthentication
to your authentication classes. -
Secure your routes with
IsAuthenticated
. -
Customize token lifetime to match your use case.
-
Use refresh tokens and rotate them securely.