0
0
DjangoHow-ToBeginner · 4 min read

How to Use JWT Authentication with DRF in Django

To use JWT authentication in Django REST Framework (DRF), install the djangorestframework-simplejwt package, add it to your INSTALLED_APPS, and configure REST_FRAMEWORK settings to use JWTAuthentication. Then, include JWT token obtain and refresh views in your URLs to handle login and token refresh.
📐

Syntax

This is the basic setup to enable JWT authentication in Django REST Framework:

  • Install the package djangorestframework-simplejwt.
  • Add rest_framework_simplejwt.authentication.JWTAuthentication to your DEFAULT_AUTHENTICATION_CLASSES in settings.py.
  • Include token obtain and refresh views in your urls.py to get and refresh JWT tokens.
python
INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework_simplejwt',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

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'),
]
💻

Example

This example shows a minimal Django project setup with JWT authentication enabled. It demonstrates how to obtain a token by posting username and password, and how to use the token to access a protected API view.

python
# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_simplejwt',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

# urls.py
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected_view(request):
    return Response({'message': f'Hello, {request.user.username}! This is a protected view.'})

urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/protected/', protected_view, name='protected'),
]

# Usage:
# 1. POST to /api/token/ with JSON {"username": "youruser", "password": "yourpass"} to get access and refresh tokens.
# 2. Use the access token in Authorization header as "Bearer <token>" to GET /api/protected/.
Output
{"message": "Hello, youruser! This is a protected view."}
⚠️

Common Pitfalls

Common mistakes when using JWT with DRF include:

  • Not installing or adding rest_framework_simplejwt to INSTALLED_APPS.
  • Forgetting to set JWTAuthentication in DEFAULT_AUTHENTICATION_CLASSES.
  • Not including the token obtain and refresh URLs, so you cannot get tokens.
  • Using the token incorrectly in requests (must use Authorization: Bearer <token> header).
  • Not protecting views with proper permissions like IsAuthenticated.

Example of wrong and right usage:

python
# Wrong: Missing JWTAuthentication in settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
    ),
}

# Right: Correct JWTAuthentication setup
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}
📊

Quick Reference

Summary tips for JWT with DRF:

  • Install with pip install djangorestframework-simplejwt.
  • Add rest_framework_simplejwt to INSTALLED_APPS.
  • Set JWTAuthentication in DEFAULT_AUTHENTICATION_CLASSES.
  • Use /api/token/ to get tokens and /api/token/refresh/ to refresh.
  • Send token in Authorization: Bearer <token> header to access protected views.

Key Takeaways

Install and configure djangorestframework-simplejwt to enable JWT in DRF.
Add JWTAuthentication to REST_FRAMEWORK's DEFAULT_AUTHENTICATION_CLASSES.
Use TokenObtainPairView and TokenRefreshView URLs to manage tokens.
Protect API views with IsAuthenticated permission to require JWT tokens.
Send JWT tokens in Authorization header as Bearer tokens for access.