APIKeyHeader is Django Ninja’s base class for requiring an API key in an HTTP header. Unlike browser authentication, each API request carries its key instead of relying on a session cookie. section 11.2.5
Create a working authentication handler by:
- Subclassing APIKeyHeader and setting param_name to the header that carries the key. section 11.2.5
- Implementing authenticate(request, key), returning the key for a match and None for failure. section 11.2.5
- Passing one APIKeyHeader subclass instance through the auth argument on protected endpoints. section 11.2.5
Listing 11.12 Creating an authentication handler based on a key
# RiffMates/api_auth.py
from django.conf import settings
from ninja.security import APIKeyHeader
class APIKey(APIKeyHeader):
param_name = "X-API-KEY" #1
def authenticate(self, request, key):
if key == settings.NINJA_API_KEY: #2
return key #3
api_key = APIKey() #4
This listing defines an X-API-KEY handler, compares it with settings.NINJA_API_KEY, and creates the reusable api_key instance. section 11.2.5
