How to Authenticate with JWT in Django: Simple Guide
To authenticate with
JWT in Django, use the djangorestframework-simplejwt package which provides token issuing and verification. Install it, add it to your Django REST Framework settings, and use its views to obtain and verify JWT tokens for user authentication.Syntax
JWT authentication in Django typically involves these parts:
- Install package:
pip install djangorestframework-simplejwt - Settings: Add
rest_framework_simplejwt.authentication.JWTAuthenticationtoREST_FRAMEWORKauthentication classes. - URLs: Use provided views to get and refresh tokens.
- Use tokens: Send JWT in
Authorizationheader asBearer <token>.
python
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]Example
This example shows a minimal Django REST Framework setup using JWT authentication. It includes URLs to obtain and refresh tokens and a protected view that requires a valid JWT.
python
from django.urls import path from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView @api_view(['GET']) @permission_classes([IsAuthenticated]) def protected_view(request): return Response({'message': f'Hello, {request.user.username}! This is a protected view.'}) urlpatterns = [ path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/protected/', protected_view, name='protected'), ] # Settings snippet INSTALLED_APPS = [ 'rest_framework', 'rest_framework_simplejwt', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), }
Output
POST /api/token/ with {"username": "user", "password": "pass"} returns {"access": "<jwt_token>", "refresh": "<refresh_token>"}
GET /api/protected/ with header Authorization: Bearer <jwt_token> returns {"message": "Hello, user! This is a protected view."}
Common Pitfalls
Common mistakes when using JWT in Django include:
- Not adding
JWTAuthenticationtoDEFAULT_AUTHENTICATION_CLASSES, so tokens are ignored. - Forgetting to send the token in the
Authorizationheader with theBearerprefix. - Using expired tokens without refreshing them.
- Not securing the secret key used to sign tokens.
Always test token issuance and protected endpoints carefully.
python
Wrong way:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
# This will NOT authenticate JWT tokens.
Right way:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
# This enables JWT token authentication.Quick Reference
| Step | Description | Code/Command |
|---|---|---|
| 1 | Install JWT package | pip install djangorestframework-simplejwt |
| 2 | Add apps | 'rest_framework', 'rest_framework_simplejwt' in INSTALLED_APPS |
| 3 | Set authentication | 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',) |
| 4 | Add token URLs | path('api/token/', TokenObtainPairView.as_view()) |
| 5 | Send token in header | Authorization: Bearer |
Key Takeaways
Use djangorestframework-simplejwt for easy JWT authentication in Django REST Framework.
Add JWTAuthentication to REST_FRAMEWORK's DEFAULT_AUTHENTICATION_CLASSES to enable token checking.
Use TokenObtainPairView and TokenRefreshView to get and refresh JWT tokens.
Send JWT tokens in the Authorization header as 'Bearer ' for protected endpoints.
Always keep your secret key safe and handle token expiration properly.