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'toINSTALLED_APPS. - Run
python manage.py migrateto create token tables. - Configure
DEFAULT_AUTHENTICATION_CLASSESinREST_FRAMEWORKsettings to include'rest_framework.authentication.TokenAuthentication'. - Use
@authentication_classesand@permission_classesdecorators 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.authtokentoINSTALLED_APPSor forgetting to run migrations. - Not including
TokenAuthenticationinDEFAULT_AUTHENTICATION_CLASSES. - Forgetting to send the token in the
Authorizationheader with the prefixToken. - 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
| Step | Action | Details |
|---|---|---|
| 1 | Add app | Add 'rest_framework.authtoken' to INSTALLED_APPS |
| 2 | Migrate | Run 'python manage.py migrate' to create token tables |
| 3 | Configure | Set 'TokenAuthentication' in REST_FRAMEWORK DEFAULT_AUTHENTICATION_CLASSES |
| 4 | Create tokens | Generate tokens for users via shell or signals |
| 5 | Use tokens | Send token in 'Authorization: Token |
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.