from datetime import timedelta
INSTALLED_APPS += ['rest_framework_simplejwt']
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'AUTH_HEADER_TYPES': ('Bearer',),
}
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
JWT tokens provide stateless authentication for APIs. I use djangorestframework-simplejwt for token generation and validation. The TokenObtainPairView issues access and refresh tokens on login. I configure token lifetimes in settings. For protected endpoints, I use JWTAuthentication class. Refresh tokens allow getting new access tokens without re-authentication. I include user info in token payload via custom serializer. Blacklisting prevents reuse of revoked tokens. This scales better than session auth for APIs serving mobile apps or SPAs.