← Back to Chapters

Authentication: Token & JWT

? Authentication: Token & JWT

? Quick Overview

Authentication is a critical aspect of building secure APIs. Django REST Framework (DRF) provides two common methods: Token Authentication and JWT (JSON Web Tokens). These mechanisms ensure that only verified users can access protected resources.

? Key Concepts

  • Authentication verifies user identity
  • Tokens are sent with every API request
  • JWT is stateless and self-contained

? Syntax & Theory

Token Authentication uses a server-stored token mapped to a user. JWT embeds user data inside a signed token, reducing server-side storage.

? Code Examples

? View Code Example
// Install required packages
pip install djangorestframework djangorestframework-simplejwt
? View Code Example
// Enable token authentication
INSTALLED_APPS = [
'rest_framework',
'rest_framework.authtoken',
]
? View Code Example
// Create token for a user
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
user = User.objects.get(username='username')
token = Token.objects.create(user=user)
print(token.key)
? View Code Example
// JWT authentication configuration
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}

? Live Output / Explanation

Token authentication sends a static token with each request. JWT sends a time-limited access token and optionally a refresh token.

? Interactive Flow

Client → Login → Receive Token → Send Token in Header → Access API

? Interactive Simulator

Use the controls below to simulate the client-side lifecycle of a JWT.

// Console initialized. Waiting for login...

? Use Cases

  • Mobile and SPA authentication
  • Microservices security
  • Third-party API access

✅ Tips & Best Practices

  • Always use HTTPS
  • Prefer JWT for scalable systems
  • Rotate and expire tokens regularly

? Try It Yourself

  • Implement both auth methods in one project
  • Test token expiry and refresh
  • Secure endpoints with permissions