0
0
DjangoHow-ToBeginner · 4 min read

How to Use Token Authentication in Django REST Framework

To use TokenAuthentication in Django REST Framework (DRF), first add rest_framework.authtoken to your INSTALLED_APPS and run migrations. Then configure your REST framework settings to use TokenAuthentication and protect your views by requiring authentication tokens.
📐

Syntax

This is how you set up token authentication in Django REST Framework:

  • Add 'rest_framework.authtoken' to INSTALLED_APPS.
  • Run python manage.py migrate to create token tables.
  • Configure DEFAULT_AUTHENTICATION_CLASSES in REST_FRAMEWORK settings to include 'rest_framework.authentication.TokenAuthentication'.
  • Use @authentication_classes and @permission_classes decorators or set globally to protect your API views.
python
INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}
💻

Example

This example shows a simple API view protected by token authentication. Users must send their token in the Authorization header as Token <token> to access the view.

python
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

# Create token for a user (run once)
user = User.objects.create_user(username='alice', password='password123')
token = Token.objects.create(user=user)
print(f"User token: {token.key}")

# API view example
class HelloView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({"message": f"Hello, {request.user.username}!"})
Output
User token: 0123456789abcdef0123456789abcdef # When accessing GET /hello/ with header Authorization: Token 0123456789abcdef0123456789abcdef # Response: {"message": "Hello, alice!"}
⚠️

Common Pitfalls

Common mistakes when using token authentication in DRF include:

  • Not adding rest_framework.authtoken to INSTALLED_APPS or forgetting to run migrations.
  • Not including TokenAuthentication in DEFAULT_AUTHENTICATION_CLASSES.
  • Forgetting to send the token in the Authorization header with the prefix Token .
  • Using token authentication without setting proper permissions, allowing unauthorized access.
python
### Wrong: Missing TokenAuthentication in settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
    ],
}

### Right: Include TokenAuthentication
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}
📊

Quick Reference

StepActionDetails
1Add appAdd 'rest_framework.authtoken' to INSTALLED_APPS
2MigrateRun 'python manage.py migrate' to create token tables
3ConfigureSet 'TokenAuthentication' in REST_FRAMEWORK DEFAULT_AUTHENTICATION_CLASSES
4Create tokensGenerate tokens for users via shell or signals
5Use tokensSend token in 'Authorization: Token ' header to authenticate

Key Takeaways

Add 'rest_framework.authtoken' to INSTALLED_APPS and run migrations before using token authentication.
Configure REST_FRAMEWORK settings to include 'TokenAuthentication' in DEFAULT_AUTHENTICATION_CLASSES.
Protect your API views with IsAuthenticated permission to require token authentication.
Clients must send the token in the Authorization header as 'Token ' to access protected endpoints.
Common errors include missing migrations, wrong settings, or incorrect token header format.