Skip to main content

Enhanced Authentication UI for DRF Spectacular with AWS Cognito support and Django integration

Project description

DRF Spectacular Auth

🔐 Authentication UI for DRF Spectacular with AWS Cognito support

A Django package that adds a beautiful authentication panel to your DRF Spectacular (Swagger UI) documentation, with built-in support for AWS Cognito and extensible authentication providers.

✨ Features

  • 🎨 Beautiful UI: Clean, modern authentication panel that integrates seamlessly with Swagger UI
  • 🔐 AWS Cognito Support: Built-in integration with AWS Cognito User Pools
  • 📋 Token Management: Easy token copying with clipboard integration and manual fallback
  • 🎯 Auto Authorization: Automatically populates Swagger UI authorization headers
  • 🎨 Customizable: Flexible theming and positioning options
  • 🌍 i18n Ready: Multi-language support (Korean, English, Japanese)
  • 🔧 Extensible: Plugin system for additional authentication providers
  • 📦 Easy Integration: Minimal setup with sensible defaults

🚀 Quick Start

Installation

pip install drf-spectacular-auth

Basic Setup

  1. Add to your Django settings:
INSTALLED_APPS = [
    'drf_spectacular_auth',  # Add 'drf_spectacular_auth' before 'drf_spectacular'
    'drf_spectacular',
    # ... your other apps
]

# Optional: Add authentication backend for better integration
AUTHENTICATION_BACKENDS = [
    'drf_spectacular_auth.backend.SpectacularAuthBackend',
    'django.contrib.auth.backends.ModelBackend',  # Keep default backend
]

# Optional: Add middleware for automatic authentication
MIDDLEWARE = [
    # ... your existing middleware
    'drf_spectacular_auth.middleware.SpectacularAuthMiddleware',
    # ... rest of your middleware
]

DRF_SPECTACULAR_AUTH = {
    'COGNITO_REGION': 'your-aws-region',
    'COGNITO_CLIENT_ID': 'your-cognito-client-id',
    'COGNITO_CLIENT_SECRET': 'your-client-secret',  # Private client인 경우에만 필요
    
    # Optional: User management settings
    'AUTO_CREATE_USERS': True,  # Auto-create users from Cognito
    'REQUIRE_AUTHENTICATION': False,  # Require auth to access Swagger UI
}
  1. Update your URLs:
from drf_spectacular_auth.views import SpectacularAuthSwaggerView

urlpatterns = [
    path('api/auth/', include('drf_spectacular_auth.urls')),  # Authentication endpoints
    path('api/docs/', SpectacularAuthSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
    # ... your other urls
]
  1. That's it! 🎉 Your Swagger UI now has an authentication panel.

📁 Examples

Please Example Check examples/.

  • basic_usage/ - Basic Django + DRF + AWS Cognito integration example
  • cognito_integration/ - AWS Cognito integration (Not yet)
  • custom_theming/ - Custom thema example (Not yet)
  • hooks_example/ - Login and Logout hook example (Not yet)

Test

cd examples/basic_usage
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver

Check browser http://localhost:8000/docs/

🏗️ Architecture

Integration Strategies

This package offers multiple integration strategies to suit different use cases:

1. Simple Auth Panel (Default)

  • Adds authentication panel to Swagger UI
  • Minimal configuration required
  • Good for basic documentation with optional authentication

2. Middleware Integration (Recommended)

  • Automatic authentication handling
  • Session-based auth persistence
  • Better integration with existing Django auth

3. Backend Integration (Advanced)

  • Full Django user integration
  • Auto-create users from Cognito
  • Supports existing Django permission systems

Comparison with django-auth-adfs

Unlike django-auth-adfs which focuses on ADFS/Azure AD integration, this package:

  • Specializes in AWS Cognito authentication
  • Focuses on API documentation (Swagger UI) integration
  • Offers lighter-weight integration options
  • Supports both simple overlay and full Django auth integration

⚙️ Configuration

AWS Cognito Client Types

Public Client (Basic):

  • Not Client Secret
  • COGNITO_CLIENT_SECRET=None

Private Client (Enhanced):

  • Need Client Secret
  • Must have COGNITO_CLIENT_SECRET
  • Automatic calculate SECRET_HASH
# Public Client (Basic)
DRF_SPECTACULAR_AUTH = {
    'COGNITO_REGION': 'ap-northeast-2',
    'COGNITO_CLIENT_ID': 'your-public-client-id',
}

# Private Client (Enhanced)
DRF_SPECTACULAR_AUTH = {
    'COGNITO_REGION': 'ap-northeast-2',
    'COGNITO_CLIENT_ID': 'your-private-client-id',
    'COGNITO_CLIENT_SECRET': os.getenv('COGNITO_CLIENT_SECRET'),
}

Full Configuration Options

DRF_SPECTACULAR_AUTH = {
    # AWS Cognito Settings
    'COGNITO_REGION': 'ap-northeast-2',
    'COGNITO_CLIENT_ID': 'your-client-id',
    'COGNITO_CLIENT_SECRET': None,
    
    # API Endpoints
    'LOGIN_ENDPOINT': '/api/auth/login/',
    'LOGOUT_ENDPOINT': '/api/auth/logout/',
    
    # UI Settings
    'PANEL_POSITION': 'top-right',  # top-left, top-right, bottom-left, bottom-right
    'PANEL_STYLE': 'floating',      # floating, embedded
    'AUTO_AUTHORIZE': True,         # Auto-fill authorization headers
    'SHOW_COPY_BUTTON': True,       # Show token copy button
    'SHOW_USER_INFO': True,         # Show user email in panel
    
    # Theming
    'THEME': {
        'PRIMARY_COLOR': '#61affe',
        'SUCCESS_COLOR': '#28a745',
        'ERROR_COLOR': '#dc3545',
        'BACKGROUND_COLOR': '#ffffff',
        'BORDER_RADIUS': '8px',
        'SHADOW': '0 2px 10px rgba(0,0,0,0.1)',
    },
    
    # Localization
    'DEFAULT_LANGUAGE': 'ko',
    'SUPPORTED_LANGUAGES': ['ko', 'en', 'ja'],
    
    # Security
    'TOKEN_STORAGE': 'localStorage',  # localStorage, sessionStorage
    'CSRF_PROTECTION': True,
    
    # User Management
    'AUTO_CREATE_USERS': False,  # Auto-create users from successful authentication
    'CREATE_TEMP_USER': True,   # Create temporary users for documentation access
    'REQUIRE_AUTHENTICATION': False,  # Require auth to access Swagger UI
    
    # Extensibility
    'CUSTOM_AUTH_PROVIDERS': [],
    'HOOKS': {
        'PRE_LOGIN': None,
        'POST_LOGIN': None,
        'PRE_LOGOUT': None,
        'POST_LOGOUT': None,
    }
}

🎨 Customization

Custom Authentication Provider

from drf_spectacular_auth.providers.base import AuthProvider

class CustomAuthProvider(AuthProvider):
    def authenticate(self, credentials):
        # Your custom authentication logic
        return {
            'access_token': 'your-token',
            'user': {'email': 'user@example.com'}
        }
    
    def get_user_info(self, token):
        # Get user information from token
        return {'email': 'user@example.com'}

# Register your provider
DRF_SPECTACULAR_AUTH = {
    'CUSTOM_AUTH_PROVIDERS': [
        'path.to.your.CustomAuthProvider'
    ]
}

Custom Templates

DRF_SPECTACULAR_AUTH = {
    'CUSTOM_TEMPLATES': {
        'auth_panel': 'your_app/custom_auth_panel.html',
        'login_form': 'your_app/custom_login_form.html',
    }
}

🔧 Development

Local Development

git clone https://github.com/yourusername/drf-spectacular-auth.git
cd drf-spectacular-auth
pip install -e ".[dev]"

Running Tests

pytest
pytest --cov=drf_spectacular_auth

Code Quality

black .
isort .
flake8

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

📚 Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf_spectacular_auth-1.1.0.tar.gz (27.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

drf_spectacular_auth-1.1.0-py3-none-any.whl (27.5 kB view details)

Uploaded Python 3

File details

Details for the file drf_spectacular_auth-1.1.0.tar.gz.

File metadata

  • Download URL: drf_spectacular_auth-1.1.0.tar.gz
  • Upload date:
  • Size: 27.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for drf_spectacular_auth-1.1.0.tar.gz
Algorithm Hash digest
SHA256 5a1126a2469301a4c07c83ee8a81adaf296bdff8c52ab966e4b2a1c6b488b05c
MD5 c79a6a94fc7a817fbcdf750c5334c744
BLAKE2b-256 17a90fc0be79a690f5309a2ac91704db8953ef274a7c6c1cb0d4d5f7acdb2d11

See more details on using hashes here.

File details

Details for the file drf_spectacular_auth-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for drf_spectacular_auth-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4fdac021447356b24feb638729799a10378b4da5200d86ad81306b38d069ff7c
MD5 20c80f87285799a9de428f201293e328
BLAKE2b-256 7766743e40f59c7b3c35103b4d6e1a001e3e3cccea9a9bde2d13d8f364be7f12

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page