Django package for API Key authentication with Django Ninja. Secure key management with hashing, expiration, revocation, and Django user integration.
This skill provides expert guidance for developing and maintaining ninja-api-key, a Django package that implements API Key authentication for Django Ninja with enhanced security features.
ninja-api-key is a Django package forked from django-ninja-apikey that provides secure API Key authentication for Django Ninja REST framework. It integrates with Django's authentication system and uses Django's password hashing for secure key storage.
**Before implementing:**
**Implementation steps:**
1. Add model changes to `models.py` if needed
2. Create corresponding migration: `python manage.py makemigrations`
3. Update `admin.py` if admin interface changes are needed
4. Add authentication logic to `security.py` if needed
5. Write comprehensive tests in `ninja_apikey/tests/`
6. Update CHANGELOG.md with detailed description (see section 5)
7. Update documentation if user-facing changes exist
When modifying authentication logic, follow this flow:
1. **Extract key**: Get API key from `X-API-Key` header
2. **Parse key**: Split into prefix and key components using `{prefix}.{key}` format
3. **Lookup**: Find `APIKey` record by prefix
4. **Verify**: Check key against hashed value using `check_password()`
5. **Validate**: Ensure key is not revoked and not expired
6. **User check**: Verify associated user is active
7. **Set context**: Set `request.user` and return user object
**Test structure:**
**Writing tests:**
```python
import pytest
from django.test import override_settings
from ninja_apikey.models import APIKey
@pytest.mark.django_db
def test_api_key_authentication(admin_user):
# Create API key
key_data = APIKey.objects.create_key(
user=admin_user,
label="Test Key"
)
# Test authentication logic
# Use parametrized tests for multiple scenarios
```
**Run tests:**
**Before committing:**
1. Run Black formatter: `black ninja_apikey/` (line length: 88)
2. Run Ruff linter: `ruff check ninja_apikey/`
3. Check import sorting: `isort ninja_apikey/ --profile black`
4. Run pre-commit hooks: `pre-commit run --all-files`
**Code patterns:**
**Always update CHANGELOG.md** following [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format with an additional **Internal** section:
**Sections:**
**Add entries to `[Unreleased]` section:**
```markdown
```
**Breaking changes:** Flag clearly with **BREAKING:** prefix in description
**Basic API protection:**
```python
from ninja import NinjaAPI
from ninja_apikey.security import APIKeyAuth
api = NinjaAPI(auth=APIKeyAuth())
@api.get("/protected")
def protected_endpoint(request):
return f"Hello, {request.user}!"
```
**Endpoint-specific protection:**
```python
from ninja_apikey.security import APIKeyAuth
auth = APIKeyAuth()
@api.get("/specific", auth=auth)
def specific_endpoint(request):
return {"user": request.user.username}
```
**Performance optimization with custom hasher:**
```python
PASSWORD_HASHERS = [
"ninja_apikey.hashers.SHA256PasswordHasher",
"django.contrib.auth.hashers.Argon2PasswordHasher",
# ... other hashers
]
```
**Generating keys programmatically:**
```python
from ninja_apikey.models import APIKey
key_data = APIKey.objects.create_key(
user=user,
label="My API Key",
expiration_date=None # Optional expiration
)
```
**Key validation:**
1. **Security First**: Always hash keys before storage, never log or display raw keys after generation
2. **Django Compatibility**: Maintain compatibility with Django LTS versions
3. **Django Ninja Integration**: Ensure authentication works seamlessly with Django Ninja patterns
4. **Backward Compatibility**: Avoid breaking changes to model structure or authentication API
5. **Testing Required**: All code changes must include comprehensive tests
6. **Documentation**: Update CHANGELOG.md with every user-facing or internal change
```
ninja_apikey/
├── models.py # APIKey model definition
├── security.py # Authentication classes and key utilities
├── admin.py # Django admin integration
├── hashers.py # Custom password hashers
├── migrations/ # Database migrations
└── tests/
├── test_security.py
├── test_models.py
├── test_admin.py
└── test_hashers.py
```
**Core:**
**Testing:**
**Optional (enhanced hashing):**
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/ninja-api-key/raw