Django Rest Framework's Built-in Authentication Classes
Last updated 1 month, 1 week ago | 107 views 75 5

Authentication is a critical component of building secure APIs. Django Rest Framework (DRF) provides a powerful and extensible authentication system that supports multiple methods out of the box. In this article, we’ll explore DRF’s built-in authentication classes, how they work, and how to use them effectively.
What is Authentication in DRF?
Authentication determines who the user is. DRF provides built-in classes to handle this process, and these classes populate request.user
and request.auth
in your views.
DRF ships with the following authentication classes:
-
BasicAuthentication
-
SessionAuthentication
-
TokenAuthentication
Let’s break down each of them.
1. BasicAuthentication
✅ How it Works
This uses HTTP Basic Auth, where the user credentials (username and password) are encoded in the request headers.
Setup
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
class BasicAuthExample(APIView):
authentication_classes = [BasicAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'message': f'Hello {request.user}!'})
⚠️ Note
-
Sends credentials in plain text (base64 encoded).
-
Use only with HTTPS.
-
Not ideal for production APIs.
2. SessionAuthentication
✅ How it Works
Leverages Django's default session authentication. This is great for browser-based clients.
Setup
from rest_framework.authentication import SessionAuthentication
class SessionAuthExample(APIView):
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'message': f'Logged in as {request.user.username}'})
⚠️ Note
-
Only works with Django's session framework.
-
Suitable for websites (not mobile apps or third-party APIs).
3. TokenAuthentication
✅ How it Works
Uses a token string that a client includes in the request header. DRF comes with a basic token system, but you can also use libraries like djangorestframework-simplejwt
for more advanced use.
Setup
First, install rest_framework.authtoken
:
pip install djangorestframework
Add it to your INSTALLED_APPS
in settings.py
:
INSTALLED_APPS = [
...
'rest_framework.authtoken',
]
Run migrations:
python manage.py migrate
Then, create tokens for users:
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
user = User.objects.get(username='admin')
token = Token.objects.create(user=user)
print(token.key)
API View Using Token Authentication
from rest_framework.authentication import TokenAuthentication
class TokenAuthExample(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'token_user': request.user.username})
Add Login Endpoint to Get Token
from rest_framework.authtoken.views import obtain_auth_token
from django.urls import path
urlpatterns = [
path('api/token/', obtain_auth_token),
]
Sending Token in Headers
Client should send:
Authorization: Token <your_token_here>
Tips & Best Practices
-
Always Use HTTPS: Especially with
BasicAuthentication
or tokens. -
Use Token or JWT for APIs:
SessionAuthentication
is great for web, but not ideal for mobile or public APIs. -
Combine with Permissions: Use
IsAuthenticated
,IsAdminUser
, or custom permissions for better access control. -
Rotate Tokens: For better security, consider regenerating tokens periodically.
-
Use
DEFAULT_AUTHENTICATION_CLASSES
in settings:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
⚠️ Common Pitfalls
Pitfall | Explanation |
---|---|
❌ Not using HTTPS | Makes token or password sniffing easy. |
❌ Forgetting to migrate authtoken |
Token model won't be created. |
❌ Using wrong Authorization header format |
It must be Token <token> not Bearer unless you're using JWT. |
❌ Assuming SessionAuthentication works for APIs |
It’s intended for session-based authentication like Django admin. |
❌ Missing @csrf_exempt with SessionAuthentication |
CSRF check might block your request in non-browser clients. |
✅ Complete Example Project
Let’s create a minimal DRF project that uses TokenAuthentication
.
Project Structure
myproject/
├── manage.py
├── myapp/
│ ├── views.py
│ ├── urls.py
├── myproject/
│ ├── settings.py
│ ├── urls.py
settings.py
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
'myapp',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
myapp/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class HelloUser(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({'message': f'Welcome, {request.user.username}!'})
myapp/urls.py
from django.urls import path
from .views import HelloUser
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('hello/', HelloUser.as_view()),
path('api/token/', obtain_auth_token),
]
myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('myapp.urls')),
]
Test the API
-
Create a user:
python manage.py createsuperuser
-
Get token:
curl -X POST -d "username=admin&password=yourpass" http://127.0.0.1:8000/api/token/
-
Call authenticated API:
curl -H "Authorization: Token <your_token>" http://127.0.0.1:8000/api/hello/
Conclusion
DRF’s built-in authentication classes make it easy to secure your APIs. While BasicAuthentication
and SessionAuthentication
are useful in certain contexts, TokenAuthentication
is often the best choice for stateless APIs.
Choose wisely based on your use case, and always keep security best practices in mind.