Django REST Auth Token Fix
In this tutorial, you'll learn about Django REST Auth Token Fix. We cover key concepts, practical examples, and best practices.
The Problem
Session-based auth doesn't work for mobile apps or third-party API clients. You need token authentication where the client sends an API key with every request.
Quick Fix
Wrong — sessions only
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
]
}
Output: Mobile and CLI clients get 403 Forbidden. Session auth relies on cookies and CSRF tokens.
Correct — Token Authentication
# settings.py
INSTALLED_APPS = [
'rest_framework',
'rest_framework.authtoken',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
Output: Clients authenticate with Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b in the header.
Creating tokens
from rest_framework.authtoken.models import Token
# On user creation
Token.objects.create(user=user)
# Or via a signal
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Obtain token endpoint
# urls.py
from rest_framework.authtoken import views
urlpatterns = [
path('api-token-auth/', views.obtain_auth_token),
]
Output: POST /api-token-auth/ with username and password returns a token.
Custom token response
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email,
})
Prevention
- Use
rest_framework.authtokenfor simple token auth. - Generate tokens on user creation via signals.
- Always use HTTPS in production — tokens are sent in plaintext headers.
Common Mistakes with rest auth token
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world DJANGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro