Session authentication is a stateful authentication method where the server stores authentication data on the backend using sessions. It's the default authentication mechanism in Django and integrates seamlessly with Django Rest Framework (DRF) for browser-based applications.
This article covers:
-
What session authentication is
-
How it works in Django and DRF
-
Setup and usage
-
Code examples
-
Tips and pitfalls
What is Session Authentication?
Session authentication relies on server-side sessions to maintain a user's authenticated state between requests. When a user logs in, Django creates a session and stores it in the database or cache. The client stores only a session ID (usually in a cookie), which is sent with every request.
How Session Authentication Works
-
User submits credentials via login form.
-
Django verifies the credentials and creates a session.
-
A session ID is saved to a cookie in the client browser.
-
On every subsequent request, the session ID is sent back to the server via that cookie.
-
Django validates the session ID and authenticates the user.
When to Use Session Authentication
Use Case | Is Session Auth Suitable? |
---|---|
Traditional Django web apps | ✅ Yes |
DRF + Web (with forms or browsable API) | ✅ Yes |
DRF + Mobile apps / SPAs | ❌ No |
External clients (e.g., Postman, curl) | ⚠️ Limited (CSRF token required) |
Using Session Authentication in DRF
Step 1: Enable Session Auth in settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
Step 2: Use Django's Login View
To authenticate users via sessions, you can use Django’s built-in login view or a custom one.
from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
@csrf_exempt # Only for demonstration. In production, handle CSRF securely.
@require_POST
def login_view(request):
data = json.loads(request.body)
username = data.get('username')
password = data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return JsonResponse({'message': 'Logged in successfully'})
else:
return JsonResponse({'error': 'Invalid credentials'}, status=401)
Step 3: Protect API Views with SessionAuthentication
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
class DashboardView(APIView):
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'user': request.user.username})
Step 4: Add URLs
from django.urls import path
from .views import login_view, DashboardView
urlpatterns = [
path('login/', login_view),
path('dashboard/', DashboardView.as_view()),
]
Testing with Browsers vs Postman
✅ With Browser
-
When you log in via the frontend or admin, Django creates a session.
-
You can visit API views (like
/dashboard/
) using the browser, and session authentication will just work.
⚠️ With Postman or curl
-
You must manually manage cookies and send a CSRF token for POST/PUT/DELETE.
-
Otherwise, Django will block the request with a
403 Forbidden
.
✅ Complete Example
Simplified API View
class ProfileView(APIView):
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'email': request.user.email})
Using the Browsable API
DRF’s browsable API interface (via browser) supports login/logout using session authentication. You can test it by visiting /api/profile/
.
Tips & Best Practices
-
Use Session Auth with Browsers Only
It works well with Django templates and web clients, but not ideal for APIs consumed by mobile or external services. -
Handle CSRF Properly
If you're usingSessionAuthentication
, ensure your API clients (like AJAX) include CSRF tokens. -
Use HTTPS Only
Cookies and sessions are vulnerable over insecure connections. -
Separate API and Web Logins
For APIs, consider using Token or JWT instead of session-based login for flexibility.
⚠️ Common Pitfalls
Pitfall | Explanation |
---|---|
❌ CSRF token missing | SessionAuthentication requires a valid CSRF token for non-safe HTTP methods (POST, PUT, DELETE). |
❌ Doesn’t work in mobile apps | Mobile and third-party clients struggle with CSRF and session cookie handling. |
❌ Forgetting to login | You must explicitly log in users to create sessions via login() in Django views. |
❌ Expecting session to work via raw curl |
Unless you manage cookies and CSRF manually, it won’t work. |
❌ Using @csrf_exempt everywhere |
This disables an important layer of protection; use it wisely and sparingly. |
Conclusion
Session authentication is ideal when building traditional Django websites or APIs accessed through browsers. It integrates perfectly with Django’s built-in user system and the DRF browsable API.
However, for RESTful APIs designed for mobile apps or third-party clients, token-based or JWT authentication is a better choice.