0
0
DjangoHow-ToBeginner · 4 min read

How to Use Authentication in Django REST Framework (DRF)

In Django REST Framework (DRF), you enable authentication by adding authentication_classes to your views or globally in settings.py. Common authentication methods include TokenAuthentication and SessionAuthentication, which verify user identity before allowing access to API endpoints.
📐

Syntax

Authentication in DRF is set by specifying authentication_classes on views or viewsets. You can also set default authentication globally in settings.py under REST_FRAMEWORK.

Common authentication classes include:

  • rest_framework.authentication.SessionAuthentication - uses Django sessions.
  • rest_framework.authentication.TokenAuthentication - uses tokens for stateless auth.

Example syntax for a view:

python
from rest_framework.views import APIView
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

class ExampleView(APIView):
    authentication_classes = [TokenAuthentication, SessionAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'message': 'Authenticated!'})
💻

Example

This example shows how to enable token authentication in DRF. It includes setting up token authentication in settings.py, creating a user, generating a token, and protecting an API view.

python
# settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
]

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

# urls.py
from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token
from .views import ProtectedView

urlpatterns = [
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
    path('protected/', ProtectedView.as_view(), name='protected'),
]

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication

class ProtectedView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'message': f'Hello, {request.user.username}! You are authenticated.'})
Output
GET /protected/ with valid token header returns: {'message': 'Hello, username! You are authenticated.'} POST /api-token-auth/ with username and password returns: {'token': 'your_generated_token_here'}
⚠️

Common Pitfalls

Common mistakes when using authentication in DRF include:

  • Not adding rest_framework.authtoken to INSTALLED_APPS when using token authentication.
  • Forgetting to run migrations after adding token auth app.
  • Not including authentication classes in views or settings, causing endpoints to be open.
  • Using IsAuthenticated permission without authentication classes, blocking all access.
  • Not sending the token in the Authorization header as Token <token>.

Example of a wrong and right way:

python
# Wrong: Missing authentication_classes
class WrongView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'message': 'You should not see this'})

# Right: Include authentication_classes
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response

class RightView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'message': 'Authenticated access'})
📊

Quick Reference

ConceptDescriptionExample
TokenAuthenticationAuthenticate users with tokens in headers'TokenAuthentication' in authentication_classes
SessionAuthenticationAuthenticate users via Django sessions'SessionAuthentication' in authentication_classes
IsAuthenticatedPermission class to allow only logged-in users'permission_classes = [IsAuthenticated]'
obtain_auth_tokenView to get token by username/passwordpath('api-token-auth/', obtain_auth_token)
Authorization HeaderSend token as 'Token 'Authorization: Token 123abc

Key Takeaways

Set authentication_classes on views or globally in settings to enable authentication in DRF.
Use TokenAuthentication for stateless APIs and SessionAuthentication for session-based auth.
Always pair authentication_classes with permission_classes like IsAuthenticated to protect endpoints.
Add 'rest_framework.authtoken' to INSTALLED_APPS and run migrations when using token auth.
Send tokens in the Authorization header as 'Token ' for authenticated requests.