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.
Token Authentication uses a server-stored token mapped to a user. JWT embeds user data inside a signed token, reducing server-side storage.
// Install required packages
pip install djangorestframework djangorestframework-simplejwt
// Enable token authentication
INSTALLED_APPS = [
'rest_framework',
'rest_framework.authtoken',
]
// 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)
// JWT authentication configuration
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
Token authentication sends a static token with each request. JWT sends a time-limited access token and optionally a refresh token.
Client → Login → Receive Token → Send Token in Header → Access API
Use the controls below to simulate the client-side lifecycle of a JWT.