Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Django rest-framework JWT authentication
Django REST Framework JWT authentication provides a secure token-based authentication system using JSON Web Tokens. JWT tokens contain encoded user information and are ideal for stateless authentication in API applications.
Installation
First, install the required packages ?
pip install djangorestframework-simplejwt pip install djangorestframework
Configuration
Settings Configuration
In settings.py, add the following configuration ?
INSTALLED_APPS = [
# ... other apps
'rest_framework',
'rest_framework_simplejwt',
# ... other apps
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
}
This configuration sets JWT as the default authentication method and configures token lifetimes.
URL Configuration
In your project's urls.py, add the JWT authentication endpoints ?
from django.contrib import admin
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView,
)
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('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]
Creating a Protected View
Create a simple protected API view to test JWT authentication ?
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': 'Hello, authenticated user!',
'user': request.user.username
})
Authentication Flow
Key Features
| Feature | Description | Endpoint |
|---|---|---|
| Token Obtain | Get access and refresh tokens | /api/token/ |
| Token Refresh | Get new access token | /api/token/refresh/ |
| Token Verify | Validate token | /api/token/verify/ |
Usage Example
To authenticate with the API, send a POST request with credentials ?
POST /api/token/
Content-Type: application/json
{
"username": "your_username",
"password": "your_password"
}
The server returns JWT tokens ?
{
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
}
Use the access token in the Authorization header for protected requests ?
GET /api/protected/ Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...
Conclusion
Django REST Framework with SimpleJWT provides robust token-based authentication. Use access tokens for API requests and refresh tokens to obtain new access tokens when they expire. This creates a secure, stateless authentication system perfect for modern web applications.
