Django Ninja JWT

5.4.4 · active · verified Fri Apr 17

Django Ninja JWT provides JSON Web Token (JWT) authentication for Django Ninja, a fast API framework for Django. It handles token creation, refresh, and authentication seamlessly within Django Ninja API routes, building upon `djangorestframework-simplejwt`. The current version is 5.4.4, with a regular release cadence focused on bug fixes and compatibility updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `django-ninja-jwt` in a Django project. It covers adding the library to `INSTALLED_APPS`, configuring `SIMPLE_JWT` settings, specifying `AUTHENTICATION_BACKENDS`, and integrating the `AuthRouter` for token management endpoints. It also shows how to protect an API endpoint using `JWTAuth()`.

import os
from datetime import timedelta

# --- In your Django project's settings.py ---

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'your-very-secret-key-for-development') # IMPORTANT: Use a strong key in production

INSTALLED_APPS = [
    # ... other apps
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "ninja", # Add django-ninja
    "ninja_jwt", # Add this
    # ...
]

# Configure JWT settings (mimics djangorestframework-simplejwt settings)
SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), # Short lifetime for access tokens
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),  # Longer lifetime for refresh tokens
    "ROTATE_REFRESH_TOKENS": False,
    "BLACKLIST_AFTER_ROTATION": False,
    "UPDATE_LAST_LOGIN": False,
    "ALGORITHM": "HS256",
    "SIGNING_KEY": SECRET_KEY, # Crucial: use a strong, unique secret key here!
    "VERIFYING_KEY": None,
    "AUDIENCE": None,
    "ISSUER": None,
    "AUTH_HEADER_TYPES": ("Bearer",),
    "AUTH_TOKEN_CLASSES": ("ninja_jwt.tokens.AccessToken",),
    "TOKEN_TYPE_CLAIM": "token_type",
    "JTI_CLAIM": "jti",
}

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend', # For default Django user auth
    'ninja_jwt.authentication.JWTAuthBackend',   # Important for token authentication
]

# --- In your_project/urls.py (main project urls) ---

from django.contrib import admin
from django.urls import path
from ninja import NinjaAPI
from ninja_jwt.views import AuthRouter
from ninja_jwt.authentication import JWTAuth

# Create your NinjaAPI instance
api = NinjaAPI(
    version="1.0.0",
    title="My Django Ninja JWT API"
)

# Add the JWT authentication routes (e.g., /api/auth/token, /api/auth/token/refresh)
api.add_router("auth/", AuthRouter())

# Example protected endpoint
@api.get("/hello", auth=JWTAuth()) # Use JWTAuth to protect this endpoint
def protected_hello(request):
    return {"message": f"Hello, {request.user.username}! You are authenticated."}

urlpatterns = [
    path('admin/', admin.site.urls),
    path("api/", api.urls), # Mount your Ninja API
]

# To run this example:
# 1. Ensure Django and django-ninja-jwt are installed.
# 2. Add 'ninja' and 'ninja_jwt' to INSTALLED_APPS in settings.py.
# 3. Configure SIMPLE_JWT and AUTHENTICATION_BACKENDS as shown.
# 4. Run `python manage.py makemigrations` and `python manage.py migrate`.
# 5. Create a superuser: `python manage.py createsuperuser`.
# 6. Run the development server: `python manage.py runserver`.
# 7. Test:
#    - POST to /api/auth/token/ with {"username": "youruser", "password": "yourpassword"} to get tokens.
#    - GET to /api/hello/ with 'Authorization: Bearer <your_access_token>' header.

view raw JSON →