DRF Auth Kit: A Modern Type-Safe Authentication Toolkit for Django REST Framework

The Django REST Framework ecosystem has long relied on packages like dj-rest-auth and django-trench for authentication and multi-factor authentication needs. While these have served us well, the modern Django development landscape demands more: better type safety, automatic API documentation, and a more streamlined developer experience.

Today, I’m excited to introduce DRF Auth Kit – a next-generation authentication toolkit that addresses these needs while maintaining the flexibility and robustness Django developers expect.

The Problem with Current Solutions

As Django applications grow more complex and teams embrace modern development practices, existing authentication solutions show their limitations:

Type Safety Gaps: Most existing packages lack comprehensive type hints, making it difficult to catch errors early and provide good IDE support.

Documentation Overhead: Manually maintaining API documentation that stays in sync with your authentication endpoints is time-consuming and error-prone.

Configuration Complexity: Setting up multi-factor authentication or social login often requires extensive configuration and custom code.

Limited Flexibility: Switching between authentication backends (JWT, Token, custom) often requires significant code changes.

Introducing DRF Auth Kit

DRF Auth Kit is built from the ground up with modern Django and Python best practices:

:locked_with_key: Universal Authentication Backend

Instead of choosing between different authentication classes, DRF Auth Kit provides a single authentication backend that adapts to your needs:

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'auth_kit.authentication.AuthKitAuthentication',
    ],
}

AUTH_KIT = {
    'AUTH_TYPE': 'jwt',  # or 'token', 'custom'
    'USE_AUTH_COOKIE': True,
}

This single configuration works with JWT tokens, DRF tokens, or your custom authentication backend, with seamless cookie and header support.

:hammer_and_wrench: Intelligent URL Management

Conditional URL patterns - URLs automatically included/excluded based on settings:

# When USE_MFA=True, automatically creates:
# POST /api/auth/login/         # First step (password)
# POST /api/auth/login/verify/  # Second step (MFA code)
# POST /api/auth/login/change-method/
# POST /api/auth/login/resend/
# GET /api/auth/mfa/           # MFA management endpoints

# When USE_MFA=False, creates:
# POST /api/auth/login/         # Direct login

Social authentication - automatic endpoint generation:

# Just add a provider to INSTALLED_APPS:
INSTALLED_APPS = [
    'allauth.socialaccount.providers.google',
    'auth_kit.social',
]

# Automatically creates:
# POST /api/auth/social/google/
# POST /api/auth/social/google/connect/
# GET /api/auth/social/accounts/

:shield: Complete Type Safety

Every component in DRF Auth Kit includes comprehensive type hints:

# Full type safety throughout
from auth_kit.authentication import AuthKitAuthentication
from auth_kit.serializers import LoginRequestSerializer
from auth_kit.views import LoginView

Full mypy and pyright compatibility with comprehensive type hints throughout the codebase. This means better IDE support, easier debugging, and fewer runtime errors.

:books: Automatic API Documentation

Integration with DRF Spectacular provides automatic OpenAPI schema generation:

# Zero configuration needed
INSTALLED_APPS = [
    'drf_spectacular',
    'auth_kit',
]

# Your API documentation is automatically generated
# Including request/response schemas, authentication flows,
# and interactive testing interfaces

Visit /api/docs/ to see your authentication endpoints with:

  • Interactive Swagger UI
  • ReDoc documentation
  • DRF Browsable API integration
  • Complete request/response examples

:locked: Simplified Multi-Factor Authentication

MFA setup is streamlined compared to existing solutions:

# Enable MFA with minimal configuration
INSTALLED_APPS = [
    'auth_kit',
    'auth_kit.mfa',  # Add MFA support
]

AUTH_KIT = {
    'USE_MFA': True,  # URLs automatically reconfigure
}

Automatic URL reconfiguration when MFA is enabled:

  • Login endpoint becomes two-step flow
  • MFA management endpoints automatically created
  • All endpoints documented in your OpenAPI schema

This provides:

  • Email-based MFA with HTML/text templates
  • Authenticator app support (Google Authenticator, Authy, etc.)
  • Backup codes for account recovery
  • Extensible handler system for custom MFA methods

:globe_with_meridians: Enhanced Social Authentication

Social authentication integrates seamlessly with Django Allauth:

INSTALLED_APPS = [
    'auth_kit',
    'auth_kit.social',  # Automatic URL generation
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.github',
    # Add any provider, URLs created automatically!
]

# URLs are automatically created for each provider:
# POST /api/auth/social/google/
# POST /api/auth/social/github/
# POST /api/auth/social/google/connect/
# POST /api/auth/social/github/connect/
# GET /api/auth/social/accounts/

No manual URL configuration needed! The system scans your installed providers and creates endpoints automatically.

:cookie: Security-First Cookie Authentication

HTTP-only cookies with enhanced security features:

AUTH_KIT = {
    'USE_AUTH_COOKIE': True,
    'AUTH_COOKIE_SECURE': True,      # HTTPS only
    'AUTH_COOKIE_HTTPONLY': True,    # No JavaScript access
    'AUTH_COOKIE_SAMESITE': 'Lax',   # CSRF protection
}

Real-World Usage Examples

Basic Setup

# settings.py
INSTALLED_APPS = [
    'rest_framework',
    'auth_kit',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'auth_kit.authentication.AuthKitAuthentication',
    ],
}

# urls.py
urlpatterns = [
    path('api/auth/', include('auth_kit.urls')),
]

That’s it! Your API now has complete authentication endpoints with automatic documentation.

Custom Authentication Flow

# Custom login serializer
class CustomLoginSerializer(LoginRequestSerializer):
    remember_me = serializers.BooleanField(default=False)
    
    def validate(self, attrs):
        attrs = super().validate(attrs)
        # Custom validation logic
        return attrs

# Apply the customization
AUTH_KIT = {
    'LOGIN_REQUEST_SERIALIZER': 'myapp.serializers.CustomLoginSerializer',
}

MFA Implementation

# Custom MFA handler
class SMSMFAHandler(BaseMFAHandler):
    name = "sms"
    
    def send_code(self, user: User, code: str) -> None:
        # Your SMS implementation
        send_sms(user.phone, f"Your code: {code}")
    
    def verify_code(self, user: User, code: str) -> bool:
        # Verification logic
        return super().verify_code(user, code)

# Register the handler
AUTH_KIT = {
    'USE_MFA': True,
    'MFA_HANDLERS': [
        'auth_kit.mfa.handlers.app.MFAAppHandler',
        'auth_kit.mfa.handlers.email.MFAEmailHandler',
        'myapp.handlers.SMSMFAHandler',
    ],
}

Performance and Production Readiness

DRF Auth Kit is designed for production use:

  • Comprehensive test coverage (>95%) across multiple Python and Django versions
  • Internationalization support for 57 languages
  • Security best practices built-in
  • Efficient database queries with proper indexing
  • Rate limiting support (upcoming)

Migration Guide

From dj-rest-auth

# Most settings work with minimal changes
# Before
INSTALLED_APPS = ['dj_rest_auth']

# After
INSTALLED_APPS = ['auth_kit']

# Your existing API endpoints continue to work

From django-trench

# Before
INSTALLED_APPS = ['trench']

# After
INSTALLED_APPS = ['auth_kit', 'auth_kit.mfa']
AUTH_KIT = {'USE_MFA': True}

What’s Next?

The roadmap includes exciting features:

  • WebAuthn support for passwordless authentication
  • Hardware security keys (YubiKey, FIDO2)
  • Rate limiting and audit logging
  • Advanced security features and geographic restrictions

Getting Started

# Install the package
pip install drf-auth-kit

# For MFA support
pip install drf-auth-kit[mfa]

# For social authentication
pip install drf-auth-kit[social]

# For everything
pip install drf-auth-kit[all]

Check out the complete documentation for detailed setup instructions, customization guides, and API reference.

Contributing to the Django Ecosystem

DRF Auth Kit is open source and welcomes contributions from the Django community. Whether you’re interested in adding new MFA methods, improving documentation, or suggesting new features, we’d love to have you involved.

Final Thoughts

Building DRF Auth Kit has been a journey of learning from the Django community’s needs and creating something that addresses modern development challenges. While we drew inspiration from existing solutions, we’ve built something new that we believe represents the future of Django REST Framework authentication.

The combination of type safety, automatic documentation, and developer-friendly APIs makes DRF Auth Kit a natural choice for new projects and a smooth migration path for existing ones.

Try it out in your next Django project and let us know what you think! The Django community’s feedback has been invaluable in shaping this project, and we’re excited to see what you build with it.