DEV Community

Huy Nguyen
Huy Nguyen

Posted on

Building a Modern, Type-Safe Authentication System for Django REST Framework

Have you ever spent hours fighting with authentication setup in your Django REST API? Or struggled with type errors that could have been caught at development time? Or wished your API documentation would just... work automatically?

I've been there. After years of wrestling with existing Django authentication packages, I decided to build something better: DRF Auth Kit – a modern, type-safe authentication toolkit that just works.

The Problem: Authentication Shouldn't Be This Hard

Let me paint a picture. You're building a modern web app with a Django REST API backend. You need:

✅ JWT authentication with cookie support

✅ Multi-factor authentication

✅ Social login (Google, GitHub, etc.)

✅ Automatic API documentation

✅ Type safety throughout

With existing solutions, you'd typically:

  1. Install 3-4 different packages
  2. Write custom serializers and views
  3. Manually configure complex URL patterns
  4. Struggle with type hints and documentation
  5. Debug cryptic authentication errors

There had to be a better way.

The Solution: DRF Auth Kit

DRF Auth Kit is what I wish existed when I started building Django APIs. Here's what makes it different:

🎯 One Package, Everything Included

# Get everything you need
pip install drf-auth-kit[all]

# Or pick what you need
pip install drf-auth-kit[mfa]     # + Multi-factor auth
pip install drf-auth-kit[social]  # + Social authentication
Enter fullscreen mode Exit fullscreen mode

🔒 Universal Authentication Backend

Instead of juggling multiple authentication classes:

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

AUTH_KIT = {
    'AUTH_TYPE': 'jwt',  # or 'token', 'custom'
    'USE_AUTH_COOKIE': True,
    'USE_MFA': True,
}
Enter fullscreen mode Exit fullscreen mode

This single configuration handles:

  • JWT tokens with automatic refresh
  • DRF token authentication
  • Custom authentication backends
  • HTTP-only cookies with security headers
  • Multi-factor authentication

🛠️ 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
Enter fullscreen mode Exit fullscreen mode

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/
Enter fullscreen mode Exit fullscreen mode

📝 Type Safety That Actually Works

Every component includes comprehensive type hints:

from auth_kit.authentication import AuthKitAuthentication
from auth_kit.serializers import LoginRequestSerializer
from auth_kit.views import LoginView
Enter fullscreen mode Exit fullscreen mode

Full mypy and pyright compatibility with comprehensive type hints throughout the codebase. Your IDE will thank you. No more guessing what parameters a function expects or what a setting does.

📚 API Documentation That Updates Itself

Integration with DRF Spectacular means your API docs are always current:

# Zero configuration needed
INSTALLED_APPS = [
    'drf_spectacular',
    'auth_kit',
]
Enter fullscreen mode Exit fullscreen mode

Visit /api/docs/ and you'll see:

  • Interactive Swagger UI
  • Complete request/response schemas
  • Authentication flow examples
  • Working test interface

API Documentation Example

🛡️ MFA Made Simple

Multi-factor authentication that doesn't require a PhD:

# Enable MFA
INSTALLED_APPS = [
    'auth_kit',
    'auth_kit.mfa',  # Just add this!
]

AUTH_KIT = {
    'USE_MFA': True,  # URLs automatically reconfigure
}
Enter fullscreen mode Exit fullscreen mode

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

You get:

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

The login flow becomes a clean two-step process:

  1. Username/password → Get ephemeral token
  2. MFA code → Get final auth tokens

🌐 Social Authentication That Just Works

Social login with 50+ providers and automatic URL generation:

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/
Enter fullscreen mode Exit fullscreen mode

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

🍪 Security-First Cookie Authentication

HTTP-only cookies with all the 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
}
Enter fullscreen mode Exit fullscreen mode

Perfect for modern web apps where you want security without complexity.

Real-World Example: Complete Auth Setup

Here's how you'd set up a complete authentication system:

# settings.py
INSTALLED_APPS = [
    'rest_framework',
    'auth_kit',
    'auth_kit.mfa',
    'auth_kit.social',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
]

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

AUTH_KIT = {
    'AUTH_TYPE': 'jwt',
    'USE_AUTH_COOKIE': True,
    'USE_MFA': True,
}

# Social auth providers
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'},
        'OAUTH_PKCE_ENABLED': True,
        'APP': {
            'client_id': 'your-google-client-id',
            'secret': 'your-google-client-secret',
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
# urls.py
from django.urls import path, include

urlpatterns = [
    path('api/auth/', include('auth_kit.urls')),
    path('api/auth/social/', include('auth_kit.social.urls')),
]
Enter fullscreen mode Exit fullscreen mode

That's it! You now have:

  • JWT authentication with cookies
  • User registration and email verification
  • Password reset functionality
  • Multi-factor authentication
  • Social login with Google
  • Complete API documentation
  • Type safety throughout

Customization: Make It Yours

Need custom behavior? Override any component:

# Custom login serializer
class CustomLoginSerializer(LoginRequestSerializer):
    remember_me = serializers.BooleanField(default=False)

    def validate(self, attrs):
        attrs = super().validate(attrs)
        # Your custom logic here
        return attrs

# Apply it
AUTH_KIT = {
    'LOGIN_REQUEST_SERIALIZER': 'myapp.serializers.CustomLoginSerializer',
}
Enter fullscreen mode Exit fullscreen mode

Want a custom MFA method? Easy:

class SMSMFAHandler(BaseMFAHandler):
    name = "sms"

    def send_code(self, user: User, code: str) -> None:
        # Your SMS implementation
        send_sms(user.phone, f"Your verification code: {code}")

# Register it
AUTH_KIT = {
    'MFA_HANDLERS': [
        'auth_kit.mfa.handlers.app.MFAAppHandler',
        'auth_kit.mfa.handlers.email.MFAEmailHandler',
        'myapp.handlers.SMSMFAHandler',
    ],
}
Enter fullscreen mode Exit fullscreen mode

Production-Ready Features

DRF Auth Kit isn't just for prototypes:

  • Comprehensive test coverage (>95%) across multiple Python/Django versions
  • Internationalization support for 57 languages
  • Security best practices built-in
  • Performance optimized with efficient database queries
  • Rate limiting and audit logging (coming soon)

The Numbers Don't Lie

Here's how DRF Auth Kit compares to existing solutions:

Feature dj-rest-auth django-trench DRF Auth Kit
Type Safety ✅ Full mypy/pyright
Auto OpenAPI ⚠️ Partial ✅ Complete
Cookie Auth ✅ Enhanced
MFA Support ✅ Simplified
Social Auth ✅ Better integration
Custom Auth ⚠️ Complex ✅ Easy
I18n Support ✅ 57 languages
Test Coverage ⚠️ ⚠️ ✅ >95%

Try It Today

pip install drf-auth-kit[all]
Enter fullscreen mode Exit fullscreen mode

Check out the complete documentation for detailed guides, examples, and API reference.

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

Join the Community

DRF Auth Kit is open source and built by developers, for developers:

Final Thoughts

Building authentication shouldn't be a painful experience. With DRF Auth Kit, you get a modern, type-safe solution that grows with your project – from simple JWT authentication to complex multi-factor flows.

The combination of type safety, automatic documentation, and developer-friendly APIs makes it perfect for both new projects and existing ones looking to modernize their authentication.

What are you waiting for? Give it a try in your next project and let me know what you think! 🚀

Top comments (0)