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
Metadata
Release files for fastapi-identity-kit 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| fastapi_identity_kit-0.2.0.tar.gz | 212.7 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| fastapi_identity_kit-0.2.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 367.4 kB
Release files / fastapi_identity_kit-0.2.0.tar.gz
| Download URL | fastapi_identity_kit-0.2.0.tar.gz |
|---|---|
| Size | 212.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
30f5e02c15413171423f599ce781747199b6311bbdbb86e82ba0bd29c707aac1
|
|
BLAKE2b-256 checksum How to use checksums |
160d2a1f7ff957dbbf44ce89788e151deab4a29e9d045d23666b62c0a44c7388
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.9
|
Release files / fastapi_identity_kit-0.2.0-py3-none-any.whl
| Download URL | fastapi_identity_kit-0.2.0-py3-none-any.whl |
|---|---|
| Size | 154.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5c49135a0da2960c90cbab7fde5ac8dbeab8ad8ab0a08478fc3f79774e110700
|
|
BLAKE2b-256 checksum How to use checksums |
6a05be73dfbe353e014b9204be48913fa0fb5494e238114cd7aeb314c86de9f4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.9
|
Security for fastapi-identity-kit 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.