liveBook · Manning

APIKeyHeader

As explained in Django in Action

APIKeyHeader is a Django Ninja security base class for implementing API-key authentication from an HTTP header.

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

How Django in Action covers it

How deep it goes
Specifies the header name, authenticate method, return values, instance placement, and configuration requirement, but defers key management.
Examples
Uses RiffMates/api_auth.py, the X-API-KEY header, and settings.NINJA_API_KEY as concrete implementation elements.
What it assumes
Assumes basic Django configuration and HTTP headers while teaching the API-key handler structure from its required components.
What you can do after
Build it from scratch by subclassing APIKeyHeader and attaching one configured instance to protected endpoints.
How it connects
Connects Django Ninja authentication with HTTP headers, API keys, endpoints, sessions, and Django settings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.