Authentication
- Secure Django REST APIs using Token and JWT authentication.
What is Authentication in DRF?
Authentication is the process of verifying who the user is.
Ensures only authorized users can access certain APIs
Works together with permissions to control access
Why Authentication is Important?
Protects sensitive data
Prevents unauthorized access
Used in mobile apps, web apps, and external integrations
Types of Authentication in DRF
Session Authentication
What is Session Authentication?
Default in Django
Relies on login sessions
Works well for web apps where browser stores session
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
]
}
Description
API uses Django session
User must be logged in via Django login
Example Session Auth View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class DashboardAPI(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({
"message": f"Hello {request.user.username}, welcome to your dashboard"
})
Description
Only logged-in users can access
request.user → Current authenticated user
Returns personalized data
Token Authentication
What is Token Authentication?
Stateless authentication
Each user has a unique token
Client sends token in HTTP header
Perfect for mobile apps & REST clients
Install Token Auth
pip install djangorestframework
Add Token Auth
settings.py
INSTALLED_APPS = [
'rest_framework',
'rest_framework.authtoken',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
Generate Tokens for Users
python manage.py drf_create_token <username>
Description
Generates token per user
Token can be stored on client-side
Token Auth View Example
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
class ProfileAPI(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({
"username": request.user.username,
"email": request.user.email
})
Description
Sends token in HTTP header
Authorization: Token <user-token>
Returns user-specific info
Token Auth Workflow
User logs in → gets token
Client stores token (mobile app / frontend)
Each API request sends token in header
Server validates token → allows access
Session Auth vs Token Auth