Authentication

  • Secure Django REST APIs using Token and JWT authentication.
  • What is Authentication in DRF?

    Authentication is the process of verifying who the user is.

    • Ensures only authorized users can access certain APIs

    • Works together with permissions to control access

    Why Authentication is Important?

    • Protects sensitive data

    • Prevents unauthorized access

    • Used in mobile apps, web apps, and external integrations

    Types of Authentication in DRF

    Authentication Type

    Description

    Session Authentication

    Uses Django’s default session (cookies)

    Token Authentication

    Uses a unique token for each user (stateless, mobile-friendly)

    JWT Authentication

    JSON Web Tokens (advanced, optional)

    Session Authentication

    What is Session Authentication?

    • Default in Django

    • Relies on login sessions

    • Works well for web apps where browser stores session

settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
    ]
}
  • Description

    • API uses Django session

    • User must be logged in via Django login

Example Session Auth View

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

class DashboardAPI(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({
            "message": f"Hello {request.user.username}, welcome to your dashboard"
        })
	
  • Description

    • Only logged-in users can access

    • request.user → Current authenticated user

    • Returns personalized data

    Token Authentication

    What is Token Authentication?

    • Stateless authentication

    • Each user has a unique token

    • Client sends token in HTTP header

    • Perfect for mobile apps & REST clients

Install Token Auth

pip install djangorestframework

Add Token Auth

settings.py

INSTALLED_APPS = [
    'rest_framework',
    'rest_framework.authtoken',
]
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

Generate Tokens for Users

python manage.py drf_create_token <username>
  •  Description

    • Generates token per user

    • Token can be stored on client-side

Token Auth View Example

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 ProfileAPI(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({
            "username": request.user.username,
            "email": request.user.email
        })
  •  Description

    • Sends token in HTTP header

    Authorization: Token <user-token>

    • Returns user-specific info

    Token Auth Workflow

    1. User logs in → gets token

    2. Client stores token (mobile app / frontend)

    3. Each API request sends token in header

    4. Server validates token → allows access

    Session Auth vs Token Auth

    Feature

    Session Auth

    Token Auth

    Stateful

    Yes

    No

    Storage

    Browser session

    Client-side token

    Best For

    Web apps

    Mobile apps / REST clients

    Expiration

    Session timeout

    Optional / manual

    Headers

    Cookies

    Authorization header