A production-grade OAuth2/OpenID Connect identity provider built with FastAPI, featuring comprehensive security, multi-factor authentication, and enterprise-ready deployment options.
Project description
FastAPI Identity Provider
A production-grade OAuth2/OpenID Connect identity provider built with FastAPI, featuring comprehensive security, multi-factor authentication, and enterprise-ready deployment options.
Quick Start
Installation
# Install with uv (recommended)
uv add fastapi-identity-kit
# Or with pip
pip install fastapi-identity-kit
Basic Usage
from fastapi_identity_kit import create_identity_app, IdentityConfig
# Quick setup with defaults
app = create_identity_app(
database_url="postgresql://user:password@localhost/identity",
redis_url="redis://localhost:6379/0",
secret_key="your-secret-key"
)
# Run the app
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Add to Existing FastAPI App
from fastapi import FastAPI
from fastapi_identity_kit import add_identity_provider, IdentityConfig
app = FastAPI(title="My Application")
# Add identity provider
identity_config = IdentityConfig(
database_url="postgresql://user:password@localhost/identity",
redis_url="redis://localhost:6379/0",
secret_key="your-secret-key"
)
identity_app = add_identity_provider(app, config=identity_config)
@app.get("/")
async def root():
return {"message": "My Application with Identity"}
Features
Security Features
- OAuth2 Authorization Code Flow with PKCE (S256)
- OpenID Connect Core 1.0 compliance
- JWT RS256 signing with automated key rotation
- Refresh token rotation with replay attack prevention
- Multi-factor authentication (TOTP) with distributed lockout
- Risk-based adaptive authentication and device fingerprinting
- HTTPS enforcement with HSTS preload
- Database column-level encryption with key rotation
- Secret management integration (Vault, AWS Secrets Manager)
Architecture
- Microservices-ready with clear separation of concerns
- Multi-tenant support with RBAC and tenant isolation
- Scalable design with Redis caching and connection pooling
- Comprehensive monitoring with Prometheus metrics and structured logging
- Flexible deployment (direct Python, Docker, cloud-native)
Testing & Security
- Comprehensive security testing with automated CI/CD pipeline
- Token fuzzing and replay attack prevention tests
- Static analysis with Bandit, Safety, and Semgrep
- Container security scanning with Trivy and Grype
- Dynamic security testing with OWASP ZAP and Nuclei
Documentation
- Usage Guide - Complete integration guide and examples
- Architecture - System architecture and security controls
- Security - Security policy and disclosure procedures
- Threat Model - Comprehensive threat analysis
- Production Deployment - Production setup guide
Configuration
Environment Variables
# Database
DATABASE_URL=postgresql://user:password@localhost/identity
REDIS_URL=redis://localhost:6379/0
# Security
SECRET_KEY=your-super-secret-key
ENFORCE_HTTPS=true
JWT_EXPIRY_MINUTES=60
REFRESH_TOKEN_DAYS=30
# Secret Management
SECRET_PROVIDER=environment # or vault, aws
VAULT_URL=https://vault.example.com
VAULT_TOKEN=your-vault-token
Configuration Object
from fastapi_identity_kit import IdentityConfig
config = IdentityConfig(
database_url="postgresql://user:password@localhost/identity",
redis_url="redis://localhost:6379/0",
secret_key="your-secret-key",
enforce_https=True,
jwt_expiry_minutes=60,
refresh_token_days=30,
mfa_issuer="MyApp",
rate_limit_requests=100,
key_rotation_enabled=True,
database_encryption_enabled=True
)
OAuth2/OIDC Endpoints
OAuth2 Endpoints
POST /oauth/authorize # Authorization endpoint
POST /oauth/token # Token endpoint
POST /oauth/revoke # Token revocation
POST /oauth/introspect # Token introspection
OpenID Connect Endpoints
GET /.well-known/openid-configuration # OIDC discovery
GET /.well-known/jwks.json # JWKS endpoint
GET /oauth/userinfo # User information
Management Endpoints
POST /auth/login # Login endpoint
POST /auth/logout # Logout endpoint
POST /auth/register # User registration
POST /auth/mfa/setup # MFA setup
POST /auth/mfa/verify # MFA verification
Deployment Options
Option 1: Direct Python Deployment
uv add fastapi-identity-kit
uvicorn main:app --host 0.0.0.0 --port 8000 --ssl-keyfile key.pem --ssl-certfile cert.pem
Option 2: Docker Containerization
FROM python:3.11-slim
RUN pip install uv
WORKDIR /app
COPY requirements.txt .
RUN uv pip install --no-cache -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Option 3: Cloud Native
- Serverless: AWS Lambda, Vercel, Railway
- PaaS: Heroku, Render, DigitalOcean App Platform
- Kubernetes: Full orchestration support
Development
Setup Development Environment
# Clone repository
git clone https://github.com/your-repo/fastapi-identity-kit.git
cd fastapi-identity-kit
# Install dependencies
uv sync
# Run tests
uv run pytest
# Run security tests
uv run pytest -m security
# Run with coverage
uv run pytest --cov=fastapi_identity_kit
Project Structure
fastapi_identity_kit/
├── config/ # Configuration management
│ ├── settings.py # Environment-based configuration
│ └── secret_manager.py # Secret management abstraction
├── identity_core/ # Core identity functionality
│ ├── auth_service.py # Authentication logic
│ ├── password_service.py # Password hashing and validation
│ └── models.py # SQLAlchemy models
├── identity_server/ # OAuth2/OIDC server
│ ├── router.py # OAuth2 endpoints
│ └── token_service.py # JWT token management
├── mfa/ # Multi-factor authentication
│ ├── totp.py # TOTP implementation
│ └── lockout.py # Distributed lockout
├── authorization/ # Authorization and RBAC
│ └── rbac.py # Role-based access control
├── risk_engine/ # Risk analysis and adaptive auth
│ └── analyzer.py # Risk scoring engine
├── shared_security/ # Shared security components
│ ├── jwt_engine.py # JWT signing/verification
│ ├── key_manager.py # Key management
│ ├── pkce.py # PKCE implementation
│ ├── crypto_utils.py # Cryptographic utilities
│ ├── middleware.py # Security middleware
│ ├── https_middleware.py # HTTPS enforcement
│ ├── key_rotation.py # Automated key rotation
│ └── database_encryption.py # Database encryption
└── app_factory.py # Application factory
Security
This identity provider implements comprehensive security measures:
- Defense in Depth: Multiple security layers with independent controls
- Zero Trust: All requests are authenticated and authorized
- Encryption: Data encrypted at rest and in transit
- Key Management: Automated key rotation with secure storage
- Audit Logging: Comprehensive security event logging
- Rate Limiting: Protection against brute force attacks
- Input Validation: Comprehensive input sanitization and validation
For detailed security information, see SECURITY.md and THREAT_MODEL.md.
Monitoring & Observability
Prometheus Metrics
# Authentication metrics
auth_requests_total{status="success|failure"}
auth_duration_seconds
mfa_attempts_total{result="success|failure"}
# Token metrics
tokens_issued_total{type="access|refresh"}
tokens_validated_total{result="valid|invalid"}
key_rotation_events_total
# Security metrics
security_events_total{type="replay|brute_force|suspicious"}
rate_limit_hits_total
encryption_operations_total
Health Checks
GET /health # Application health
GET /health/database # Database connectivity
GET /health/redis # Redis connectivity
GET /health/vault # Secret store connectivity
Testing
Run All Tests
uv run pytest
Run Security Tests Only
uv run pytest -m security
Run with Coverage
uv run pytest --cov=fastapi_identity_kit --cov-report=html
Performance Testing
uv run locust -f tests/performance/locustfile.py
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Security Contributions
For security vulnerabilities, please follow the disclosure policy in SECURITY.md.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- FastAPI - Modern, fast web framework for building APIs
- OAuth 2.0 - The OAuth 2.0 authorization framework
- OpenID Connect - OpenID Connect Core 1.0 specification
- PyJWT - JSON Web Token implementation in Python
Support
- Documentation: Full documentation
- Usage Guide: Complete integration examples
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Security: Report security issues to security@example.com
Built for secure, scalable identity management
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_identity_kit-0.2.0.tar.gz.
File metadata
- Download URL: fastapi_identity_kit-0.2.0.tar.gz
- Upload date:
- Size: 212.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
30f5e02c15413171423f599ce781747199b6311bbdbb86e82ba0bd29c707aac1
|
|
| MD5 |
30edc7a54fc3489869b5af37d65122cf
|
|
| BLAKE2b-256 |
160d2a1f7ff957dbbf44ce89788e151deab4a29e9d045d23666b62c0a44c7388
|
File details
Details for the file fastapi_identity_kit-0.2.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_identity_kit-0.2.0-py3-none-any.whl
- Upload date:
- Size: 154.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5c49135a0da2960c90cbab7fde5ac8dbeab8ad8ab0a08478fc3f79774e110700
|
|
| MD5 |
99c546ac6077c45c304430eccee06763
|
|
| BLAKE2b-256 |
6a05be73dfbe353e014b9204be48913fa0fb5494e238114cd7aeb314c86de9f4
|