Skip to content

lucasrcezimbra/ninja-api-key

Repository files navigation

Ninja API Key

PyPI

codecov

API Key authentication for Django Ninja.

This is a fork from django-ninja-apikey.

Key Features:

  • Easy integration into your projects
  • Well integrated with the Admin interface
  • Secure API keys due to hashing
  • Works with the standard user model

Installation

pip install ninja-api-key

How to use

  1. Add ninja_apikey to your installed apps in your Django project:
# settings.py

INSTALLED_APPS = [
    # ...
    "ninja_apikey",
]
  1. Apply migrations
python manage.py migrate
  1. Secure

    a. the whole API

    # api.py
    
    from ninja import NinjaAPI
    from ninja_apikey.security import APIKeyAuth
    
    #  ...
    
    api = NinjaAPI(auth=APIKeyAuth())
    
    # ...
    
    @api.get("/secure_endpoint")
    def secure_endpoint(request):
        return f"Hello, {request.user}!"

    b. an specific endpoint

    # api.py
    
    from ninja import NinjaAPI
    from ninja_apikey.security import APIKeyAuth
    
    #  ...
    
    auth = APIKeyAuth()
    api = NinjaAPI()
    
    # ...
    
    @api.get("/secure_endpoint", auth=auth)
    def secure_endpoint(request):
        return f"Hello, {request.user}!"
  2. ninja-api-key uses settings.PASSWORD_HASHERS to hash the API keys. Django's default PBKDF2PasswordHasher may be slow depending on the number of iterations. You can change the settings.PASSWORD_HASHERS to use a faster (but less secure) one. ninja-api-key provides a SHA256PasswordHasher.

     # settings.py
    
     PASSWORD_HASHERS = [
         "ninja_apikey.hashers.SHA256PasswordHasher",
         # others
     ]

    ⚠️ Keep in mind that this will affect Django authentication as a whole, not just ninja-api-key.

Contributing

Contributions are welcome; feel free to open an Issue or Pull Request.

git clone https://github.com/lucasrcezimbra/ninja-api-key
cd ninja-api-key
python -m venv .venv
source .venv/bin/activate
pip install .[test]
pre-commit install
make test