### Complete Router Setup Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md A comprehensive example showing the setup of multiple routers and protected routes in a Django project. ```python # api.py from ninja import NinjaAPI from ninja_jwt.routers.obtain import obtain_pair_router from ninja_jwt.routers.verify import verify_router from ninja_jwt.authentication import JWTAuth # Create API instance api = NinjaAPI(auth=JWTAuth()) # Add JWT routes api.add_router('/auth', obtain_pair_router) api.add_router('/auth', verify_router) # Your protected routes @api.get('/protected') def protected_view(request): return {'user_id': request.user.id} # urls.py from django.urls import path from api import api urlpatterns = [ path('api/', api.urls), ] # Now endpoints: # POST /api/auth/pair - Get tokens # POST /api/auth/refresh - Refresh access token # POST /api/auth/verify - Verify token # GET /api/protected - Protected endpoint (needs auth) ``` -------------------------------- ### get_verifying_key Method Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example showing how to get the verifying key, particularly for RSA/ECDSA algorithms with JWK_URL. ```python backend = TokenBackend( 'RS256', verifying_key=open('public.pem').read() ) key = backend.get_verifying_key(token) ``` -------------------------------- ### Example Usage of get() Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Illustrates using the get method to retrieve a claim with a default value. ```python token = AccessToken() username = token.get('username', 'anonymous') ``` -------------------------------- ### Stateless Authentication Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of using stateless authentication and accessing token claims. ```python from ninja_jwt.authentication import JWTStatelessUserAuthentication # No database lookup - user data from token claims auth = JWTStatelessUserAuthentication() user = auth.authenticate(request, token) # Returns TokenUser # Access token claims as properties print(user.id) # From 'user_id' claim print(user.username) # From 'username' claim ``` -------------------------------- ### Login Flow Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of a user login request and response, including storing tokens. ```python # User login POST /token/pair { "username": "john", "password": "secret" } → { "access": "eyJ...", "refresh": "eyJ...", "username": "john" } # Store both tokens on client # Use access token in Authorization header # Use refresh token to get new access token ``` -------------------------------- ### Installing Cryptographic Dependencies Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/getting_started.md Command to install django-ninja-jwt with optional cryptographic support for RSA and ECDSA algorithms. ```bash pip install django-ninja-jwt[crypto] ``` -------------------------------- ### Custom Schema Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of creating a custom schema for token obtain input and response. ```python from ninja_jwt.schema import TokenObtainInputSchemaBase from ninja import Schema class CustomLoginSchema(TokenObtainInputSchemaBase): @classmethod def get_response_schema(cls): return CustomResponseSchema @classmethod def get_token(cls, user): # Custom token generation logic return {'access': str(...), 'refresh': str(...)} # Register in settings NINJA_JWT = { 'TOKEN_OBTAIN_PAIR_INPUT_SCHEMA': 'myapp.schema.CustomLoginSchema', } ``` -------------------------------- ### Example Usage of Dictionary-like Access Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Illustrates setting, getting, and deleting claims using dictionary-like syntax. ```python token = AccessToken() token['user_id'] = 123 # Set claim user_id = token['user_id'] # Get claim del token['custom_claim'] # Delete claim ``` -------------------------------- ### Token Refresh Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of refreshing an access token when it expires. ```python # When access token expires POST /token/refresh { "refresh": "eyJ..." } → { "access": "eyJ...", "refresh": null # Only if ROTATE_REFRESH_TOKENS enabled } ``` -------------------------------- ### Token Verification Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of verifying a token's validity without decoding. ```python # Verify token is valid (no decode) POST /token/verify { "token": "eyJ..." } → {} # 200 OK or 401 if invalid ``` -------------------------------- ### Logout Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of blacklisting a refresh token for logout. ```python # Blacklist refresh token (if blacklist app enabled) POST /token/blacklist { "refresh": "eyJ..." } → {} # 200 OK ``` -------------------------------- ### TokenBackend Initialization Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example of how to instantiate the TokenBackend with specific algorithm, signing key, and leeway. ```python from ninja_jwt.backends import TokenBackend from datetime import timedelta backend = TokenBackend( algorithm='HS256', signing_key='your-secret-key', leeway=timedelta(seconds=30), ) ``` -------------------------------- ### Custom Token Class Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of creating a custom token class with additional validation. ```python from ninja_jwt.tokens import Token from datetime import timedelta class CustomToken(Token): token_type = 'custom' lifetime = timedelta(hours=1) def verify(self): super().verify() # Add custom validation if 'required_claim' not in self.payload: raise TokenError("Missing required claim") # Register in settings NINJA_JWT = { 'AUTH_TOKEN_CLASSES': ('myapp.tokens.CustomToken',), } ``` -------------------------------- ### Install flit Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/development_and_contributing.md Installs the flit build tool, which is necessary for development. ```shell $(venv) pip install flit ``` -------------------------------- ### Get Tokens Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example cURL request to obtain access and refresh tokens by sending user credentials. ```bash curl -X POST http://localhost:8000/api/token/pair \ -H "Content-Type: application/json" \ -d '{"username": "john", "password": "secret"}' # Response { "access": "eyJ0eXAiOiJKV1QiLCJhbGc...", "refresh": "eyJ0eXAiOiJKV1QiLCJhbGc...", "username": "john" } ``` -------------------------------- ### Install development libraries and pre-commit hooks Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/development_and_contributing.md Installs all necessary development libraries and sets up pre-commit hooks for code linting and style checks. ```shell $(venv) make install ``` -------------------------------- ### Complete Token Flow Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example demonstrating the complete flow of creating, encoding, decoding, and verifying a JWT token using TokenBackend. ```python from ninja_jwt.backends import TokenBackend from datetime import datetime, timedelta, timezone # Create backend backend = TokenBackend( algorithm='HS256', signing_key='my-secret-key', leeway=10, ) # Create token payload now = datetime.now(timezone.utc) payload = { 'user_id': 123, 'token_type': 'access', 'exp': int((now + timedelta(minutes=5)).timestamp()), 'iat': int(now.timestamp()), 'jti': 'unique-id-123', } # Encode token token = backend.encode(payload) print(f"Token: {token}") # Decode and verify token decoded = backend.decode(token) print(f"User ID: {decoded['user_id']}") # Decode without verification (unsafe - only for inspection) unverified = backend.decode(token, verify=False) ``` -------------------------------- ### Verification Router Usage Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md An example of how to add the verify_router to a NinjaAPI instance. ```python from ninja import NinjaAPI from ninja_jwt.routers.verify import verify_router api = NinjaAPI() api.add_router('/auth', verify_router) # Now available: # POST /auth/verify ``` -------------------------------- ### Accessing Settings Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example of how to import and access settings using `api_settings`. ```python from ninja_jwt.settings import api_settings # Access any setting lifetime = api_settings.ACCESS_TOKEN_LIFETIME algorithm = api_settings.ALGORITHM auth_rule = api_settings.USER_AUTHENTICATION_RULE ``` -------------------------------- ### Sliding Token Router Usage Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md An example demonstrating the configuration and usage of the sliding_router. ```python from ninja import NinjaAPI from ninja_jwt.routers.obtain import sliding_router from ninja_jwt.settings import api_settings # Configure for sliding tokens NINJA_JWT = { 'AUTH_TOKEN_CLASSES': ('ninja_jwt.tokens.SlidingToken',), } api = NinjaAPI() api.add_router('/auth', sliding_router) # Now available: # POST /auth/sliding # POST /auth/sliding/refresh ``` -------------------------------- ### Refreshing Access Token Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/getting_started.md Example using curl to POST a refresh token and obtain a new access token. ```bash curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"}' \ http://localhost:8000/api/token/refresh/ ...{"access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZX...", "refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVm..."} ``` -------------------------------- ### Authentication Class Usage Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of how to integrate JWTAuth into your NinjaAPI instance. ```python from ninja import NinjaAPI from ninja_jwt.authentication import JWTAuth api = NinjaAPI(auth=JWTAuth()) @api.get("/protected") def protected_view(request): return {"user_id": request.user.id} ``` -------------------------------- ### Obtain Access and Refresh Tokens Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/getting_started.md Example using curl to POST user credentials and obtain JWT access and refresh tokens. ```bash curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "davidattenborough", "password": "boatymcboatface"}' \ http://localhost:8000/api/token/pair ... { "access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU", "refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4" ``` -------------------------------- ### Accessing Global Backend Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example of accessing the global token backend instance. ```python from ninja_jwt.state import token_backend # Use global backend payload = token_backend.decode(token_string) ``` -------------------------------- ### Complete Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/INDEX.md A comprehensive example demonstrating the configuration of NINJA_JWT in settings.py, setting up the API with JWT authentication, defining protected endpoints, and illustrating usage patterns for login, token refresh, and logout. ```python # settings.py from datetime import timedelta NINJA_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), 'ALGORITHM': 'HS256', 'SIGNING_KEY': 'your-secret-key', } INSTALLED_APPS = [ 'ninja_jwt', 'ninja_jwt.token_blacklist', ] # api.py from ninja import NinjaAPI from ninja_jwt.controller import NinjaJWTDefaultController from ninja_extra import NinjaExtraAPI from ninja_jwt.authentication import JWTAuth # Setup api = NinjaExtraAPI(auth=JWTAuth()) api.register_controllers(NinjaJWTDefaultController) # Protected endpoints @api.get('/protected') def protected_view(request): return {'user_id': request.user.id} # urls.py from django.urls import path from api import api urlpatterns = [ path('api/', api.urls), ] # Usage # 1. Login: POST /api/token/pair {"username": "john", "password": "secret"} # 2. Response: {"access": "eyJ...", "refresh": "eyJ...", "username": "john"} # 3. Use: GET /api/protected with header "Authorization: Bearer eyJ..." # 4. Refresh: POST /api/token/refresh {"refresh": "eyJ..."} # 5. Logout: POST /api/token/blacklist {"refresh": "eyJ..."} ``` -------------------------------- ### blacklist example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Example usage of the blacklist method. ```python from ninja_jwt.tokens import RefreshToken refresh = RefreshToken.for_user(user) blacklist_record = refresh.blacklist() ``` -------------------------------- ### get_leeway Method Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example demonstrating how to retrieve the leeway value from a TokenBackend instance. ```python backend = TokenBackend('HS256', signing_key='secret', leeway=30) leeway = backend.get_leeway() print(leeway) # 0:00:30 ``` -------------------------------- ### Adding Custom Claims to Token Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of how to add custom claims to a token object. ```python token = AccessToken() token['custom_claim'] = 'custom_value' token['user_id'] = user.id ``` -------------------------------- ### Example Usage of __str__() Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Shows how to get the encoded string representation of a token. ```python token = AccessToken() token['user_id'] = user.id encoded = str(token) # Send encoded token to client ``` -------------------------------- ### default_user_authentication_rule example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/authentication.md Example of how to use the default_user_authentication_rule function. ```python from ninja_jwt.authentication import default_user_authentication_rule if default_user_authentication_rule(user): # User can authenticate pass ``` -------------------------------- ### Testing Protected Endpoint Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of how to test a protected endpoint using Django's TestClient and a JWT AccessToken. ```python from ninja.testing import TestClient from ninja_jwt.tokens import AccessToken from django.contrib.auth import get_user_model User = get_user_model() def test_protected_endpoint(): user = User.objects.create_user('john', 'pass') token = AccessToken.for_user(user) client = TestClient(api) response = client.get('/protected', headers={ 'Authorization': f'Bearer {token}' }) assert response.status_code == 200 ``` -------------------------------- ### decode Method Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example showing how to decode a JWT token and handle potential TokenBackendError exceptions. ```python from ninja_jwt.backends import TokenBackend from ninja_jwt.exceptions import TokenBackendError backend = TokenBackend('HS256', signing_key='secret') try: payload = backend.decode(token) user_id = payload['user_id'] except TokenBackendError as e: print(f"Decode failed: {e}") ``` -------------------------------- ### AsyncJWTAuth example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/authentication.md Example of how to use the AsyncJWTAuth class to authenticate a request. ```python from ninja_jwt.authentication import AsyncJWTAuth from django.http import HttpRequest auth = AsyncJWTAuth() request = HttpRequest() user = await auth.authenticate(request, token="eyJ0eXAiOiJKV1QiLCJhbGc...") ``` -------------------------------- ### settings.py Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example settings.py configuration for django-ninja-jwt, including INSTALLED_APPS and NINJA_JWT settings. ```python from datetime import timedelta INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', # ... other apps 'ninja_jwt', 'ninja_jwt.token_blacklist', # Optional, for token blacklisting ] NINJA_JWT = { # Token lifetimes 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), # Refresh token rotation 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': True, # JWT algorithm and keys 'ALGORITHM': 'HS256', 'SIGNING_KEY': 'your-secret-key-here', # User and claims 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', # Authentication 'USER_AUTHENTICATION_RULE': 'ninja_jwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('ninja_jwt.tokens.AccessToken',), 'TOKEN_USER_CLASS': 'ninja_jwt.models.TokenUser', # Token validation 'LEEWAY': 0, 'AUDIENCE': None, 'ISSUER': None, } ``` -------------------------------- ### access_token example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Example usage of the access_token property. ```python from ninja_jwt.tokens import RefreshToken refresh = RefreshToken.for_user(user) access = refresh.access_token print(f"Access token: {access}") ``` -------------------------------- ### Customizing Token Controllers Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/getting_started.md Demonstrates how to inherit from TokenObtainPairController to create a custom controller for token operations. ```python from ninja_extra import api_controller from ninja_jwt.controller import TokenObtainPairController @api_controller('token', tags=['Auth']) class MyCustomController(TokenObtainPairController): """obtain_token and refresh_token only""" ... api.register_controllers(MyCustomController) ``` -------------------------------- ### for_user example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Example usage of for_user to create access and refresh tokens. ```python from ninja_jwt.tokens import AccessToken, RefreshToken from django.contrib.auth import get_user_model User = get_user_model() user = User.objects.get(username='john') access = AccessToken.for_user(user) refresh = RefreshToken.for_user(user) ``` -------------------------------- ### Installation Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/README.md Install Ninja JWT using pip. ```shell pip install django-ninja-jwt ``` -------------------------------- ### AuthenticationFailed Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example of catching AuthenticationFailed during JWT authentication. ```python from ninja_jwt.authentication import JWTAuth from ninja_jwt.exceptions import AuthenticationFailed auth = JWTAuth() try: user = auth.jwt_authenticate(request, token) except AuthenticationFailed as e: print(f"Auth failed: {e.detail}") ``` -------------------------------- ### Decoded Access Token Structure Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of the structure of a decoded access token. ```json { "token_type": "access", "user_id": 1, "username": "john", "is_staff": false, "is_superuser": false, "exp": 1634567890, "iat": 1634567500, "jti": "a1b2c3d4e5f6..." } ``` -------------------------------- ### Use Token Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example cURL request to access a protected endpoint using an access token. ```bash curl -H "Authorization: Bearer " \ http://localhost:8000/api/protected-endpoint ``` -------------------------------- ### Obtain Token Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/controllers.md Example request and response for the POST /token/sliding endpoint. ```json # POST /token/sliding { "username": "john", "password": "secret123" } # Response (200) { "token": "eyJ0eXAiOiJKV1QiLCJhbGc...", "username": "john" } ``` -------------------------------- ### encode Method Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example demonstrating how to encode a payload dictionary into a JWT token using the TokenBackend. ```python from ninja_jwt.backends import TokenBackend backend = TokenBackend('HS256', signing_key='secret') payload = { 'user_id': 123, 'token_type': 'access', 'exp': 1634567890, } token = backend.encode(payload) # Returns: "eyJ0eXAiOiJKV1QiLCJhbGc..." ``` -------------------------------- ### Obtain Pair Router Usage Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md A practical example of how to add the obtain_pair_router to a NinjaAPI instance. ```python from ninja import NinjaAPI from ninja_jwt.routers.obtain import obtain_pair_router api = NinjaAPI() api.add_router('/auth', obtain_pair_router) # Now available: # POST /auth/pair # POST /auth/refresh ``` -------------------------------- ### Bearer Token Authentication cURL Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example cURL command demonstrating how to use bearer token authentication. ```bash curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc..." \ http://api.example.com/protected-endpoint ``` -------------------------------- ### NinjaJWTSettings Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Shows how to import and use NinjaJWTSettings, a Pydantic BaseSettings class for configuration validation. ```python from ninja_jwt.settings import NinjaJWTSettings, api_settings ``` -------------------------------- ### TokenUser Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/models.md Example of creating and using a TokenUser instance. ```python from ninja_jwt.models import TokenUser from ninja_jwt.tokens import AccessToken token = AccessToken('eyJ0eXAiOiJKV1QiLCJhbGc...') user = TokenUser(token) print(user.username) # From token claims ``` -------------------------------- ### Example Usage of set_exp() Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Demonstrates setting a custom lifetime and expiration from a specific time. ```python from datetime import timedelta, datetime token = AccessToken() # Set custom lifetime token.set_exp(lifetime=timedelta(hours=2)) # Set from specific time token.set_exp(from_time=datetime.now(), lifetime=timedelta(hours=1)) ``` -------------------------------- ### JWTBaseAuthentication.get_user Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/authentication.md Example of how to retrieve a user from a validated token using JWTBaseAuthentication.get_user. ```python from ninja_jwt.authentication import JWTBaseAuthentication from django.http import HttpRequest auth = JWTBaseAuthentication() validated_token = auth.get_validated_token(raw_token) user = auth.get_user(validated_token) print(f"Authenticated user: {user.username}") ``` -------------------------------- ### TokenBackendError Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example of catching TokenBackendError during token decoding. ```python from ninja_jwt.backends import TokenBackend from ninja_jwt.exceptions import TokenBackendError backend = TokenBackend('RS256', signing_key=key) try: payload = backend.decode(token) except TokenBackendError as e: print(f"Backend error: {e}") ``` -------------------------------- ### POST /token/verify Request Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON request body for verifying a token. ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjMyMDAwMDAwfQ.signature" } ``` -------------------------------- ### Settings Import Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Import for accessing API settings. ```python from ninja_jwt.settings import api_settings ``` -------------------------------- ### ROTATE_REFRESH_TOKENS Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example of how to enable issuing a new refresh token when a new access token is issued. ```python NINJA_JWT = { 'ROTATE_REFRESH_TOKENS': True, # Issue new refresh token on refresh } ``` -------------------------------- ### POST /token/sliding/refresh Error Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON response for a token refresh error. ```json { "detail": "Token 'refresh_exp' claim has expired" } ``` -------------------------------- ### POST /token/sliding/refresh Response Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON response for a successful sliding token refresh. ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoic2xpZGluZyIsImV4cCI6MTYzMjAwMDAxMDB9.signature" } ``` -------------------------------- ### JWTAuth.authenticate Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/authentication.md Example of using JWTAuth to authenticate a request with a JWT token. ```python from ninja_jwt.authentication import JWTAuth from django.http import HttpRequest auth = JWTAuth() request = HttpRequest() auth.authenticate(request, token="eyJ0eXAiOiJKV1QiLCJhbGc...") # request.user is now set to authenticated user ``` -------------------------------- ### RSA Algorithms (Asymmetric) Configuration Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example configuration for RSA algorithms in Django settings. ```python NINJA_JWT = { 'ALGORITHM': 'RS256', 'SIGNING_KEY': open('private.pem').read(), 'VERIFYING_KEY': open('public.pem').read(), } ``` -------------------------------- ### POST /token/sliding Response Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON response for a successful sliding token obtainment. ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoic2xpZGluZyIsImV4cCI6MTYzMjAwMDAwMH0.signature", "username": "john_doe" } ``` -------------------------------- ### JWTStatelessUserAuthentication.authenticate Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/authentication.md Example of using JWTStatelessUserAuthentication for stateless authentication with a JWT token. ```python from ninja_jwt.authentication import JWTStatelessUserAuthentication auth = JWTStatelessUserAuthentication() request = HttpRequest() user = auth.authenticate(request, token="eyJ0eXAiOiJKV1QiLCJhbGc...") # user is TokenUser instance, not from database ``` -------------------------------- ### TokenUser __eq__() and __ne__() Methods Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/models.md Example of comparing TokenUser instances. ```python user1 = TokenUser(token1) user2 = TokenUser(token2) if user1 == user2: print("Same user") ``` -------------------------------- ### BLACKLIST_AFTER_ROTATION and ROTATE_REFRESH_TOKENS Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example showing how to enable blacklisting of old refresh tokens when rotation is enabled, requiring 'ninja_jwt.token_blacklist' in INSTALLED_APPS. ```python INSTALLED_APPS = [ ... 'ninja_jwt.token_blacklist', ... ] NINJA_JWT = { 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, # Blacklist old tokens } ``` -------------------------------- ### POST /token/sliding/refresh Request Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON payload for refreshing a sliding token. ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoic2xpZGluZyIsImV4cCI6MTYzMjAwMDAwMH0.signature" } ``` -------------------------------- ### JWTBaseAuthentication.jwt_authenticate Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/authentication.md Example of how to authenticate a user using a token and set it on the request object with JWTBaseAuthentication.jwt_authenticate. ```python from django.http import HttpRequest from ninja_jwt.authentication import JWTBaseAuthentication auth = JWTBaseAuthentication() request = HttpRequest() user = auth.jwt_authenticate(request, raw_token) assert request.user == user ``` -------------------------------- ### Refresh Sliding Token Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/controllers.md Example request and response for the POST /token/sliding/refresh endpoint. ```json # POST /token/sliding/refresh { "token": "eyJ0eXAiOiJKV1QiLCJhbGc..." } # Response (200) { "token": "eyJ0eXAiOiJKV1QiLCJhbGc..." } ``` -------------------------------- ### POST /token/verify Response Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON response body for a successful token verification request (empty). ```json {} ``` -------------------------------- ### Invalid Credentials Error Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example of an AuthenticationFailed error for invalid credentials. ```text AuthenticationFailed: "No active account found with the given credentials" ``` -------------------------------- ### POST /token/refresh Request Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON request body for refreshing an access token. ```json { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYzMjA4NjQwMH0.signature" } ``` -------------------------------- ### POST /token/pair Request Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON request body for obtaining access and refresh tokens. ```json { "username": "john_doe", "password": "secure_password_123" } ``` -------------------------------- ### TokenUser __str__() Method Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/models.md Example of using the __str__ method of TokenUser. ```python user = TokenUser(token) print(str(user)) # "TokenUser 123" ``` -------------------------------- ### OutstandingToken usage examples Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/models.md Examples demonstrating how to query and use the OutstandingToken model. ```python from ninja_jwt.token_blacklist.models import OutstandingToken # Find token by jti outstanding = OutstandingToken.objects.get(jti='token-id-123') # Find all tokens for user user_tokens = OutstandingToken.objects.filter(user=user) # Find expired tokens from django.utils import timezone expired = OutstandingToken.objects.filter(expires_at__lt=timezone.now()) ``` -------------------------------- ### Access any setting Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Demonstrates how to access various settings provided by the api_settings singleton. ```python lifetime = api_settings.ACCESS_TOKEN_LIFETIME algorithm = api_settings.ALGORITHM auth_rule = api_settings.USER_AUTHENTICATION_RULE ``` -------------------------------- ### ACCESS_TOKEN_LIFETIME Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example of how to configure ACCESS_TOKEN_LIFETIME to set access tokens to be valid for 30 minutes. ```python NINJA_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30), # 30-minute access tokens } ``` -------------------------------- ### SchemaControl Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Demonstrates how to use the SchemaControl helper class to manage configurable schemas and access available schemas like pair_schema and verify_schema. ```python from ninja_jwt.schema_control import SchemaControl from ninja_jwt.settings import api_settings schema = SchemaControl(api_settings) # Access schemas pair_schema = schema.obtain_pair_schema verify_schema = schema.verify_schema ``` -------------------------------- ### POST /token/pair Response Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON response body for a successful token pair request. ```json { "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjMyMDAwMDAwfQ.signature", "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYzMjA4NjQwMH0.signature", "username": "john_doe" } ``` -------------------------------- ### POST /token/refresh Response Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/endpoints.md Example JSON response body for a successful token refresh request. ```json { "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjMyMDAwMDAwfQ.signature", "refresh": null } ``` -------------------------------- ### TokenBackend Initialization Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Illustrates the initialization of the TokenBackend with various settings, including algorithm, signing key, verifying key, audience, issuer, JWK URL, leeway, and JSON encoder. ```python token_backend = TokenBackend( api_settings.ALGORITHM, api_settings.SIGNING_KEY, api_settings.VERIFYING_KEY, api_settings.AUDIENCE, api_settings.ISSUER, api_settings.JWK_URL, api_settings.LEEWAY, api_settings.JSON_ENCODER, ) ``` -------------------------------- ### UPDATE_LAST_LOGIN Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example of how to enable updating the user's 'last_login' field upon token obtain. ```python NINJA_JWT = { 'UPDATE_LAST_LOGIN': True, } ``` -------------------------------- ### InvalidToken Exception Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Examples of raising the InvalidToken exception with a custom string message or a dictionary for detailed errors. ```python from ninja_jwt.exceptions import InvalidToken # With custom message raise InvalidToken("Token expired at 2023-12-31") # With dict detail containing code raise InvalidToken({"detail": "Custom message", "code": "custom_code"}) ``` -------------------------------- ### Global Token Backend Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Shows how to access the singleton token backend instance for encoding and decoding JWT payloads. ```python from ninja_jwt.state import token_backend # Encode payload = {'user_id': 123, 'exp': ...} token = token_backend.encode(payload) # Decode decoded = token_backend.decode(token) ``` -------------------------------- ### BlacklistedToken usage examples Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/models.md Examples demonstrating how to check for blacklisted tokens and blacklist tokens. ```python from ninja_jwt.token_blacklist.models import BlacklistedToken # Check if token is blacklisted is_blacklisted = BlacklistedToken.objects.filter(token__jti='token-id').exists() # Blacklist a token (via Token.blacklist() method, preferred) from ninja_jwt.tokens import RefreshToken refresh = RefreshToken(token_string) blacklist_record = refresh.blacklist() # Query blacklisted tokens blacklisted = BlacklistedToken.objects.all() ``` -------------------------------- ### Import Callable Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Shows how to use the import_callable utility to import functions from dotted path strings. ```python from ninja_jwt.utils import import_callable # Import from string path callable_obj = import_callable('ninja_jwt.authentication.default_user_authentication_rule') # Return as-is if already callable callable_obj = import_callable(some_function) ``` -------------------------------- ### Custom Auth Implementation Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/auth_integration.md Provides an example of a custom authentication implementation by inheriting from `JWTBaseAuthentication` and using an API key in the header. ```python from ninja.security import APIKeyHeader from ninja_jwt.authentication import JWTBaseAuthentication from ninja import router class ApiKey(APIKeyHeader, JWTBaseAuthentication): param_name = "X-API-Key" def authenticate(self, request, key): return self.jwt_authenticate(request, token=key) header_key = ApiKey() router = router('') @router.get("/headerkey", auth=header_key) def apikey(request): return f"Token = {request.auth}" ``` -------------------------------- ### Invalid Credentials Request Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example JSON request with incorrect username and password. ```json { "username": "wrong_user", "password": "wrong_password" } ``` -------------------------------- ### Invalid Credentials Response Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example JSON response for invalid credentials. ```json { "detail": "No active account found with the given credentials" } ``` -------------------------------- ### ECDSA Algorithms (Asymmetric) Configuration Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example configuration for ECDSA algorithms in Django settings. ```python NINJA_JWT = { 'ALGORITHM': 'ES256', 'SIGNING_KEY': open('private.pem').read(), 'VERIFYING_KEY': open('public.pem').read(), } ``` -------------------------------- ### HMAC Algorithms (Symmetric) Configuration Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example configuration for HMAC algorithms in Django settings. ```python NINJA_JWT = { 'ALGORITHM': 'HS256', 'SIGNING_KEY': 'your-secret-key-at-least-256-bits', } ``` -------------------------------- ### Decoded Refresh Token Structure Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of the structure of a decoded refresh token. ```json { "token_type": "refresh", "user_id": 1, "username": "john", "exp": 1637159500, "iat": 1634567500, "jti": "f6e5d4c3b2a1..." } ``` -------------------------------- ### Example Usage of Token Constructor Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/tokens.md Demonstrates creating new tokens, parsing existing tokens with verification, and skipping verification. ```python from ninja_jwt.tokens import Token, AccessToken # Create new token for user token = AccessToken() token['user_id'] = user.id # Parse existing token try: token = AccessToken('eyJ0eXAiOiJKV1QiLCJhbGc...') except TokenError as e: print(f"Invalid token: {e}") # Skip verification for specific use cases token = AccessToken('eyJ0eXAiOiJKV1QiLCJhbGc...', verify=False) ``` -------------------------------- ### ISSUER Claim Configuration Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example of how to configure the ISSUER claim in settings. ```python ISSUER: Optional[str] = None The `iss` (issuer) claim to include in and validate tokens. **Type**: `Optional[str]` **Default**: None (not included) **Example**: ```python NINJA_JWT = { 'ISSUER': 'https://auth.example.com', } # Token payload will include: # {"iss": "https://auth.example.com", ...} ``` **Source**: `ninja_jwt/settings.py:46` ``` -------------------------------- ### Token Error Decorator Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Demonstrates the usage of the token_error decorator to handle TokenError exceptions. ```python from ninja_jwt.utils import token_error from ninja_jwt.exceptions import TokenError, InvalidToken @token_error def validate_token(values): if not values.get('token'): raise TokenError("Token is required") return values ``` -------------------------------- ### settings.py Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/customizing_token_claims.md Example of customizing token claims by swapping schemas in settings.py. ```python NINJA_JWT = { # FOR OBTAIN PAIR 'TOKEN_OBTAIN_PAIR_INPUT_SCHEMA': "project.schema.MyTokenObtainPairInputSchema", 'TOKEN_OBTAIN_PAIR_REFRESH_INPUT_SCHEMA': "for.obtain_pair.refresh_input.schema", # FOR SLIDING TOKEN 'TOKEN_OBTAIN_SLIDING_INPUT_SCHEMA': "for.obtain_sliding.input.schema", 'TOKEN_OBTAIN_SLIDING_REFRESH_INPUT_SCHEMA': "for.obtain_pair.refresh_input.schema", 'TOKEN_BLACKLIST_INPUT_SCHEMA': "for.blacklist_input.schema", 'TOKEN_VERIFY_INPUT_SCHEMA': "for.verify_input.schema", } ``` -------------------------------- ### JWK_URL Configuration Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example of how to configure the JWK_URL for dynamic public key retrieval. ```python JWK_URL: Optional[AnyUrl] = None URL to JWK Set for dynamic public key retrieval. Useful for validating tokens from external issuers (e.g., Auth0). **Type**: `Optional[str | URL]` **Default**: None (not used) **Requires**: PyJWT >= 2.0 **Example**: ```python NINJA_JWT = { 'ALGORITHM': 'RS256', 'JWK_URL': 'https://yourdomain.auth0.com/.well-known/jwks.json', } ``` **Source**: `ninja_jwt/settings.py:47` ``` -------------------------------- ### Inactive User Account Request Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example JSON request with credentials for an inactive user. ```json { "username": "inactive_user", "password": "correct_password" } ``` -------------------------------- ### Custom Authentication Rule Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Example of defining a custom authentication rule to check if a user's email is verified and active. ```python def require_verified_email(user): return user.is_active and user.email_verified NINJA_JWT = { 'USER_AUTHENTICATION_RULE': 'myapp.auth.require_verified_email', } ``` -------------------------------- ### Integration with Token Class Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Example showing how the Token class integrates with TokenBackend for token creation and parsing. ```python from ninja_jwt.tokens import AccessToken # Token class automatically uses the backend token = AccessToken() token['user_id'] = 123 # Encoding uses backend.encode() encoded = str(token) # Parsing uses backend.decode() parsed = AccessToken(encoded) ``` -------------------------------- ### InvalidToken Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example of catching InvalidToken for an expired token. ```python from ninja_jwt.exceptions import InvalidToken try: token = AccessToken(expired_token) except InvalidToken as e: # Response: {"detail": "Token is invalid or expired", "code": "token_not_valid"} pass ``` -------------------------------- ### TokenBackend Constructor Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/backends.md Initializes the TokenBackend with various configuration options for JWT handling. ```python def __init__( self, algorithm: str, signing_key: Optional[str] = None, verifying_key: str = "", audience: Optional[str] = None, issuer: Optional[str] = None, jwk_url: Optional[str] = None, leeway: Union[float, int, timedelta] = None, json_encoder: Optional[Type[json.JSONEncoder]] = None, ) -> None: ``` -------------------------------- ### TokenError Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Example of catching TokenError during manual token validation. ```python from ninja_jwt.tokens import AccessToken from ninja_jwt.exceptions import TokenError try: token = AccessToken(raw_token) except TokenError as e: print(f"Token validation failed: {e}") ``` -------------------------------- ### Backend Imports Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Imports for TokenBackend and the singleton instance token_backend. ```python from ninja_jwt.backends import TokenBackend from ninja_jwt.state import token_backend # Singleton instance ``` -------------------------------- ### DetailDictMixin Initialization Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/errors.md Python code defining the DetailDictMixin with default detail and code attributes, and an __init__ method. ```python class DetailDictMixin: default_detail: str default_code: str def __init__(self, detail=None, code=None) -> None ``` -------------------------------- ### Add to INSTALLED_APPS Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Configure your Django settings to include 'ninja_jwt' and optionally 'ninja_jwt.token_blacklist'. ```python # settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', # ... other apps 'ninja_jwt', 'ninja_jwt.token_blacklist', # Optional ] ``` -------------------------------- ### JWTBaseAuthentication.get_validated_token Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/authentication.md Example of how to validate an encoded JWT token using JWTBaseAuthentication.get_validated_token. ```python from ninja_jwt.authentication import JWTBaseAuthentication from ninja_jwt.tokens import AccessToken try: validated_token = JWTBaseAuthentication.get_validated_token(raw_token) except InvalidToken as e: # Handle invalid token print(f"Token validation failed: {e.detail}") ``` -------------------------------- ### Token Class Methods Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Demonstrates common methods for interacting with token objects. ```python # Token Class Methods: # - Token() — Create new token # - Token(raw_token) — Parse and validate token # - Token.for_user(user) — Create token for user # - token['claim'] — Access/set claims # - str(token) — Encode to JWT string # - token.verify() — Validate token ``` -------------------------------- ### Run tests Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/development_and_contributing.md Executes the project's test suite. ```shell $(venv) make test ``` -------------------------------- ### CallableBool Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Demonstrates the usage of CallableBool, CallableTrue, and CallableFalse for boolean-like objects that are also callable, maintaining backward compatibility. ```python from ninja_jwt.compat import CallableBool, CallableTrue, CallableFalse # Can be used as boolean if CallableTrue: print("True") # Can be called as function (deprecated) result = CallableTrue() # Still works ``` -------------------------------- ### Run tests with coverage Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/docs/development_and_contributing.md Runs the test suite and generates a code coverage report. ```shell $(venv) make test-cov ``` -------------------------------- ### REFRESH_TOKEN_LIFETIME Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/configuration.md Example of how to configure REFRESH_TOKEN_LIFETIME to set refresh tokens to be valid for 2 weeks. ```python NINJA_JWT = { 'REFRESH_TOKEN_LIFETIME': timedelta(weeks=2), # 2-week refresh tokens } ``` -------------------------------- ### Custom Authentication Implementation Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md An example of creating a custom authentication function using utilities like import_callable and aware_utcnow, along with accessing API settings and handling exceptions. ```python from ninja_jwt.utils import import_callable, aware_utcnow from ninja_jwt.settings import api_settings from ninja_jwt.exceptions import InvalidToken def custom_authenticate(token_string): """Custom token authentication""" from ninja_jwt.tokens import AccessToken try: token = AccessToken(token_string) except Exception as e: raise InvalidToken(str(e)) # Load user authentication rule auth_rule = import_callable( api_settings.USER_AUTHENTICATION_RULE ) # Get user User = get_user_model() user_id = token[api_settings.USER_ID_CLAIM] user = User.objects.get(pk=user_id) # Check auth rule if not auth_rule(user): raise InvalidToken("User failed authentication rule") return user ``` -------------------------------- ### TokenUser username Property Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/models.md Example of accessing the username property of a TokenUser. ```python user = TokenUser(token) print(user.username) # "john" or "" ``` -------------------------------- ### TokenUser id Property Example Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/models.md Example of accessing the id property of a TokenUser. ```python user = TokenUser(token) print(user.id) # Returns token['user_id'] ``` -------------------------------- ### Algorithm and Keys Configuration Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/reference-guide.md Configuration options for JWT algorithm, signing keys, verification keys, audience, issuer, JWK URL, and leeway. ```python NINJA_JWT = { 'ALGORITHM': 'HS256', # or RS256, ES256, etc. 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, # Required for RS256/ES256 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, } ``` -------------------------------- ### API Settings Singleton Usage Source: https://github.com/eadwincode/django-ninja-jwt/blob/master/_autodocs/routers-and-utilities.md Shows how to use the API Settings Singleton throughout the application to access settings like access token lifetime and token backend class. ```python from ninja_jwt.settings import api_settings # Use throughout application access_lifetime = api_settings.ACCESS_TOKEN_LIFETIME token_backend_class = api_settings.TOKEN_BACKEND ```