Authentication in APIs

Authentication in APIs ensures that only authorized users can access or modify data.

In Django REST Framework (DRF), authentication verifies who the user is, and permissions decide what the user can do.

APIs commonly use token-based authentication instead of session-based authentication.

Why API Authentication is Important

Authentication helps:

Protect sensitive data
Prevent unauthorized access
Secure user accounts
Control access to resources
Build professional and secure applications

Types of Authentication in DRF

Django REST Framework supports multiple authentication methods:

  • Session Authentication
  • Token Authentication
  • JWT Authentication
  • Basic Authentication

Let’s understand the most common ones.

1. Session Authentication

This is used mainly for web applications.

It works with Django’s login system.

In settings.py:

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

This works well for web browsers but is not ideal for mobile apps.

2. Token Authentication (Most Common)

Token authentication is widely used for APIs and mobile applications.

Step 1: Install Token Support

Add to INSTALLED_APPS:

INSTALLED_APPS = [
...
'rest_framework.authtoken',
]

Run migration:

python manage.py migrate

Step 2: Configure Authentication

In settings.py:

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

Step 3: Generate Token for User

from rest_framework.authtoken.models import Token
from django.contrib.auth.models import Useruser = User.objects.get(username="ali")
token = Token.objects.create(user=user)
print(token.key)

You can also generate tokens automatically using signals.

Step 4: Use Token in API Request

Client sends request with header:

Authorization: Token your_token_here

Now the API will authenticate the user.

Protecting API Views

Example:

from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response@api_view(['GET'])
@permission_classes([IsAuthenticated])
def secure_api(request):
return Response({"message": "You are authenticated"})

Only authenticated users can access this API.

3. JWT Authentication

JWT (JSON Web Token) is commonly used in modern applications.

It generates:

  • Access Token
  • Refresh Token

JWT is:

  • Stateless
  • Secure
  • Scalable

Popular package:

djangorestframework-simplejwt

Install:

pip install djangorestframework-simplejwt

JWT is commonly used in mobile apps and React/Angular frontends.

Authentication vs Permission

Authentication → Who are you?
Permission → What are you allowed to do?

Example permission classes:

  • IsAuthenticated
  • IsAdminUser
  • AllowAny
  • IsAuthenticatedOrReadOnly

Example: Admin-Only API

from rest_framework.permissions import IsAdminUser@api_view(['GET'])
@permission_classes([IsAdminUser])
def admin_only(request):
return Response({"message": "Admin Access Only"})

Best Practices for API Authentication

Use HTTPS
Do not expose tokens publicly
Use JWT for scalable apps
Set token expiration
Use proper permission classes
Never store passwords in plain text

Key Takeaway

Authentication in APIs ensures secure access to data.

Django REST Framework provides powerful tools like Token Authentication and JWT to secure APIs efficiently.

By combining authentication and permissions, you can build secure and professional backend systems.

Home » PYTHON FOR WEB DEVELOPMENT (PYWEB) > REST API Development > Authentication in APIs