Refreshing JWT Tokens in Django with djangorestframework-simplejwt

Last updated 4 months ago | 457 views 75     5

Tags:- Python Django DRF

Introduction: Why Token Refreshing Matters

JWT (JSON Web Tokens) are commonly used for securing APIs in modern Django applications, especially with frontend frameworks like React, Vue, or mobile apps.

However, access tokens expire quickly (usually within minutes). If they didn’t, they’d pose a massive security risk.

That’s where refresh tokens come in — they allow the client to obtain new access tokens without asking the user to re-login.

In this guide, you’ll learn how to implement token refreshing using djangorestframework-simplejwt, the most widely used JWT package for Django REST Framework (DRF).


Understanding JWT Token Refreshing

JWT authentication uses two tokens:

Token Type Purpose Expiration (default)
Access Token Authenticates API requests 5 minutes
Refresh Token Renews the access token when expired 1 day

Instead of logging the user out once the access token expires, you can send the refresh token to obtain a new access token and continue using the app seamlessly.


⚙️ Step-by-Step: Implementing Token Refresh in Django

✅ Step 1: Install Required Packages

pip install djangorestframework-simplejwt

✅ Step 2: Configure JWT in settings.py

# 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=5),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
}

✅ Step 3: Add Token Endpoints to urls.py

# urls.py

from django.urls import path
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),  # For login
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),  # For refreshing
]

✅ Step 4: Refresh the Access Token via API

Use a tool like Postman or cURL:

Endpoint:
POST /api/token/refresh/

Request Body:

{
  "refresh": "your-refresh-token-here"
}

Response:

{
  "access": "new-access-token"
}

Use this new access token in the Authorization header:

Authorization: Bearer new-access-token

Complete Example: Django Token Refreshing Flow

views.py

Let’s protect a view using JWT:

# views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

class ProtectedView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({"message": f"Welcome, {request.user.username}!"})

urls.py (continued)

from .views import ProtectedView

urlpatterns += [
    path('api/protected/', ProtectedView.as_view(), name='protected'),
]

Now test the flow:

  1. Login with api/token/ → get access and refresh tokens.

  2. Use the access token to access api/protected/.

  3. After access token expires, use api/token/refresh/ to get a new one.


Tips & Common Pitfalls

✅ Best Practices

  • Secure your refresh tokens (e.g., store in HttpOnly cookies).

  • Rotate refresh tokens on each use for enhanced security:

SIMPLE_JWT = {
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
}
  • Blacklist old tokens on logout or when suspicious activity is detected.

  • Use HTTPS only in production environments to protect tokens from interception.


❌ Common Pitfalls

  • Not including the refresh token in the request body.

  • Forgetting to add JWTAuthentication in REST_FRAMEWORK.

  • Using expired refresh tokens.

  • Not handling refresh failures on the frontend gracefully.


Access vs Refresh Token Comparison

Feature Access Token Refresh Token
Purpose API authentication Renew access token
Expiry (default) 5 minutes 1 day
Stored On Client (short-term) Client (secure)
Rotated? Optional Optional

Summary & Takeaways

Token refreshing with djangorestframework-simplejwt helps build modern, stateless, and scalable APIs in Django.

Key Points:

  • Use /api/token/refresh/ to refresh access tokens securely.

  • Store your refresh token securely on the client.

  • Rotate refresh tokens and blacklist them if needed.

  • Protect your routes using IsAuthenticated.

By implementing token refreshing, you provide a frictionless user experience without compromising security — a win-win for developers and users alike.