A production-ready FastAPI application implementing a dual authentication system supporting both JWT-based user authentication and API key-based service-to-service authentication. Built for modern microservices architectures requiring flexible authentication strategies.
- User Authentication: JWT-based authentication for human users with access and refresh tokens
- Service Authentication: API key-based authentication for service-to-service communication
- Flexible Middleware: Support for both authentication methods in a single endpoint
- User registration and login with email/password
- Secure password hashing with bcrypt
- JWT token generation (access and refresh tokens)
- Role-based access control (RBAC)
- User profile management
- Generate secure API keys with custom permissions
- Set expiration dates and auto-expiration handling
- Revoke and renew API keys
- Permission-based access control
- Track key usage with last-accessed timestamps
- Encrypted API key storage
- Password hashing with bcrypt
- JWT token validation and expiration
- API key encryption at rest
- CORS configuration
- Rate limiting support
- Token refresh mechanism
- Clean architecture with separation of concerns
- Service layer for business logic
- Middleware for authentication
- Pydantic schemas for validation
- SQLAlchemy ORM for database operations
- Comprehensive test coverage
SecureBridge/
βββ app/
β βββ __init__.py
β βββ main.py # FastAPI application entry point
β βββ api/
β β βββ __init__.py
β β βββ deps.py # Shared dependencies
β β βββ routes/
β β βββ __init__.py
β β βββ auth.py # User authentication routes
β β βββ keys.py # API key management routes
β βββ core/
β β βββ __init__.py
β β βββ config.py # Configuration management
β β βββ database.py # Database connection
β β βββ security.py # Security utilities
β βββ middleware/
β β βββ __init__.py
β β βββ auth_middleware.py # Authentication middleware
β βββ models/
β β βββ __init__.py
β β βββ user.py # User database model
β β βββ api_key.py # API key database model
β βββ schemas/
β β βββ __init__.py
β β βββ user.py # User Pydantic schemas
β β βββ api_key.py # API key Pydantic schemas
β β βββ auth.py # Auth response schemas
β βββ services/
β βββ __init__.py
β βββ auth_service.py # Authentication business logic
βββ tests/
β βββ __init__.py
β βββ conftest.py # Test configuration
β βββ test_auth.py # Authentication tests
β βββ test_keys.py # API key tests
βββ .env.example # Environment variables template
βββ .gitignore
βββ generate_keys.py # Security key generator
βββ pyproject.toml # Project configuration
βββ requirements.txt # Python dependencies
βββ README.md
βββ SETUP.md # Quick setup guide
- Python 3.10+
- uv (recommended) or pip
- Clone the repository
git clone https://github.com/baydre/SecureBridge.git
cd SecureBridge- Install dependencies
# Using uv (recommended)
curl -LsSf https://astral.sh/uv/install.sh | sh
uv pip install -r requirements.txt
# Or using pip
pip install -r requirements.txt- Generate secure keys
python generate_keys.py- Configure environment variables
cp .env.example .env
# Edit .env with the generated keys- Run the application
uvicorn app.main:app --reloadThe API will be available at http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
POST /api/v1/auth/signup
Content-Type: application/json
{
"email": "user@example.com",
"name": "John Doe",
"password": "securepass123"
}POST /api/v1/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "securepass123"
}GET /api/v1/auth/me
Authorization: Bearer <access_token>POST /api/v1/auth/refresh
Content-Type: application/json
{
"refresh_token": "<refresh_token>"
}POST /api/v1/keys/create
Authorization: Bearer <access_token>
Content-Type: application/json
{
"service_name": "my-service",
"description": "Production API key",
"permissions": ["read:data", "write:data"],
"expires_in_days": 90
}GET /api/v1/keys/list
Authorization: Bearer <access_token>GET /api/v1/keys/verify/test
Authorization: Bearer <api_key>PATCH /api/v1/keys/{key_id}/revoke
Authorization: Bearer <access_token>PATCH /api/v1/keys/{key_id}/renew
Authorization: Bearer <access_token>
Content-Type: application/json
{
"expires_in_days": 180
}DELETE /api/v1/keys/{key_id}
Authorization: Bearer <access_token>Run the comprehensive test suite:
# Install dev dependencies
uv pip install pytest pytest-asyncio httpx
# Run all tests
pytest tests/ -v
# Run with coverage
pytest --cov=app tests/Key configuration options in .env:
# Application
APP_NAME=SecureBridge
DEBUG=True
API_VERSION=v1
# Security
SECRET_KEY=<generated-secret-key>
API_KEY_ENCRYPTION_KEY=<generated-encryption-key>
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7
# Database
DATABASE_URL=sqlite:///./securebridge.db
# API Keys
API_KEY_DEFAULT_EXPIRATION_DAYS=90
API_KEY_PREFIX=sbk_- Framework: FastAPI
- Server: Uvicorn
- Database: SQLAlchemy (supports PostgreSQL, SQLite, MySQL)
- Authentication: Python-JOSE (JWT), bcrypt (password hashing)
- Encryption: Cryptography (Fernet)
- Validation: Pydantic
- Testing: pytest, httpx
- Package Manager: uv
- Always use HTTPS in production
- Rotate API keys regularly
- Use strong, unique encryption keys
- Implement rate limiting
- Monitor authentication failures
- Keep dependencies updated
- Never commit
.envfile to version control - Use environment-specific configurations
# 1. Register new user
response = requests.post("http://localhost:8000/api/v1/auth/signup", json={
"email": "user@example.com",
"name": "John Doe",
"password": "securepass123"
})
tokens = response.json()["tokens"]
# 2. Access protected endpoint
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
response = requests.get("http://localhost:8000/api/v1/auth/me", headers=headers)# 1. Create API key (as authenticated user)
headers = {"Authorization": f"Bearer {user_access_token}"}
response = requests.post("http://localhost:8000/api/v1/keys/create",
headers=headers,
json={
"service_name": "analytics-service",
"permissions": ["read:data", "write:logs"],
"expires_in_days": 90
}
)
api_key = response.json()["api_key"]
# 2. Use API key for service authentication
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get("http://localhost:8000/api/v1/keys/verify/test", headers=headers)FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Build and run:
docker build -t securebridge .
docker run -p 8000:8000 --env-file .env securebridge- Use PostgreSQL instead of SQLite
- Set
DEBUG=False - Enable HTTPS/TLS
- Configure proper CORS origins
- Set up monitoring and logging
- Implement rate limiting
- Use environment-specific secrets
Contributions are welcome! Please follow these steps:
- 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
This project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI for the excellent web framework
- SQLAlchemy for robust ORM capabilities
- The Python community for amazing libraries
For issues and questions:
- Open an issue on GitHub
- Check the API documentation
- Token blacklisting for logout
- Email notifications for key expiration
- API key usage analytics dashboard
- Multi-factor authentication (MFA)
- OAuth2 integration
- WebSocket support with authentication
- API rate limiting per key
- Audit log endpoints
- Key rotation automation