Skip to content

About

Dual Authentication System for Users and Services

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

11 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SecureBridge

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.

🌟 Features

πŸ” Dual Authentication System

  • 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 Management

  • 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

πŸ”‘ API Key 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

πŸ›‘οΈ Security Features

  • Password hashing with bcrypt
  • JWT token validation and expiration
  • API key encryption at rest
  • CORS configuration
  • Rate limiting support
  • Token refresh mechanism

πŸ—οΈ Architecture

  • 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

πŸ“ Project Structure

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

πŸš€ Quick Start

Prerequisites

  • Python 3.10+
  • uv (recommended) or pip

Installation

  1. Clone the repository
git clone https://github.com/baydre/SecureBridge.git
cd SecureBridge
  1. 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
  1. Generate secure keys
python generate_keys.py
  1. Configure environment variables
cp .env.example .env
# Edit .env with the generated keys
  1. Run the application
uvicorn app.main:app --reload

The API will be available at http://localhost:8000

πŸ“– API Documentation

Interactive Documentation

Authentication Endpoints

User Registration

POST /api/v1/auth/signup
Content-Type: application/json

{
  "email": "user@example.com",
  "name": "John Doe",
  "password": "securepass123"
}

User Login

POST /api/v1/auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "securepass123"
}

Get Current User

GET /api/v1/auth/me
Authorization: Bearer <access_token>

Refresh Token

POST /api/v1/auth/refresh
Content-Type: application/json

{
  "refresh_token": "<refresh_token>"
}

API Key Management Endpoints

Create API Key

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
}

List API Keys

GET /api/v1/keys/list
Authorization: Bearer <access_token>

Verify API Key

GET /api/v1/keys/verify/test
Authorization: Bearer <api_key>

Revoke API Key

PATCH /api/v1/keys/{key_id}/revoke
Authorization: Bearer <access_token>

Renew API Key

PATCH /api/v1/keys/{key_id}/renew
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "expires_in_days": 180
}

Delete API Key

DELETE /api/v1/keys/{key_id}
Authorization: Bearer <access_token>

πŸ§ͺ Testing

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/

πŸ”§ Configuration

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_

πŸ—οΈ Tech Stack

  • 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

πŸ”’ Security Best Practices

  1. Always use HTTPS in production
  2. Rotate API keys regularly
  3. Use strong, unique encryption keys
  4. Implement rate limiting
  5. Monitor authentication failures
  6. Keep dependencies updated
  7. Never commit .env file to version control
  8. Use environment-specific configurations

πŸ“Š Usage Examples

Example 1: User Authentication Flow

# 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)

Example 2: Service-to-Service Authentication

# 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)

🚒 Deployment

Using Docker

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

Production Considerations

  • 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

🀝 Contributing

Contributions are welcome! Please follow these steps:

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

πŸ“ License

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

πŸ™ Acknowledgments

  • FastAPI for the excellent web framework
  • SQLAlchemy for robust ORM capabilities
  • The Python community for amazing libraries

πŸ“§ Support

For issues and questions:

πŸ—ΊοΈ Roadmap

  • 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

About

Dual Authentication System for Users and Services

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages