APIs consumed by mobile applications (Flutter, React Native) and modern frontend SPAs cannot rely on browser session cookies due to cross-origin limitations. JWT (JSON Web Tokens) with djangorestframework-simplejwt is the industry-standard stateless authentication solution.
# Install SimpleJWT
pip install djangorestframework-simplejwt
# mywebsite/settings.py
from datetime import timedelta
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'AUTH_HEADER_TYPES': ('Bearer',),
}
# mywebsite/urls.py
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView,
)
urlpatterns = [
# Submit username/password -> returns access & refresh tokens
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
# Submit refresh token -> returns new access token
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
# Verify token validity
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]
# blog/permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""Custom permission to only allow owners of an object to edit or delete it."""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request (GET, HEAD, OPTIONS)
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the author
return obj.author.user == request.user
Clients send the access token in the standard HTTP header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Broaden your backend architecture, REST API design, and production engineering expertise:
Protect API endpoints from unauthorized client access.
Generate JWT tokens containing custom user claims and roles.
Protect JWT tokens from interception and implement token rotation.
Technical interview questions on session auth vs token auth vs JWT.