Authentication (Token, Session, JWT)
DRF supports multiple authentication methods: session-based (for browser clients), token-based (for API clients), and JWT (JSON Web Tokens) for stateless authentication. Each has its use case.
20 min•By Priygop Team•Updated 2026
Auth Methods
- SessionAuthentication — Uses Django sessions (browser clients)
- TokenAuthentication — Simple token in header (API clients)
- JWT (SimpleJWT) — Stateless tokens with expiry (recommended)
- BasicAuthentication — Username/password in header (testing only)
- Set per-view or globally in REST_FRAMEWORK settings
- Token: Authorization: Token abc123...
- JWT: Authorization: Bearer eyJ...
Token & JWT Auth
Token & JWT Auth
# Token Authentication Setup
# pip install djangorestframework
# INSTALLED_APPS = [..., 'rest_framework.authtoken']
# python manage.py migrate # Creates token table
# Generate token for user
# from rest_framework.authtoken.models import Token
# token = Token.objects.create(user=user)
# # Client sends: Authorization: Token abc123...
# JWT Authentication (recommended)
# pip install djangorestframework-simplejwt
# settings.py
# REST_FRAMEWORK = {
# 'DEFAULT_AUTHENTICATION_CLASSES': [
# 'rest_framework_simplejwt.authentication.JWTAuthentication',
# ],
# }
# from rest_framework_simplejwt.views import (
# TokenObtainPairView, TokenRefreshView
# )
# urlpatterns = [
# path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'),
# path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
# ]
# Client flow:
# 1. POST /api/token/ {username, password} -> {access, refresh}
# 2. Use access token: Authorization: Bearer eyJ...
# 3. When expired: POST /api/token/refresh/ {refresh} -> {access}Tip
Tip
Use SimpleJWT for stateless auth. Access tokens expire quickly (5min), refresh tokens last longer (1 day). Store securely.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Storing JWT tokens in localStorage. Use httpOnly cookies for security. localStorage is vulnerable to XSS attacks.
Practice Task
Note
(1) Install djangorestframework-simplejwt. (2) Add token endpoints. (3) Test with access and refresh tokens.
Quick Quiz
Key Takeaways
- DRF supports multiple authentication methods: session-based (for browser clients), token-based (for API clients), and JWT (JSON Web Tokens) for stateless authentication.
- SessionAuthentication — Uses Django sessions (browser clients)
- TokenAuthentication — Simple token in header (API clients)
- JWT (SimpleJWT) — Stateless tokens with expiry (recommended)