An open API service indexing awesome lists of open source software.

https://github.com/samanshafagh/python-fastapi-auth-microservice

Production-ready authentication microservice built with FastAPI. Features JWT auth, Google & GitHub OAuth2, role-based access control, PostgreSQL, Dockerized deployment, Alembic migrations, and 95%+ test coverage. Designed for secure, scalable backend systems.
https://github.com/samanshafagh/python-fastapi-auth-microservice

api-security backend docker fastapi jwt microservice oauth2 postgresql pytest python sqlalchemy

Last synced: 27 days ago
JSON representation

Production-ready authentication microservice built with FastAPI. Features JWT auth, Google & GitHub OAuth2, role-based access control, PostgreSQL, Dockerized deployment, Alembic migrations, and 95%+ test coverage. Designed for secure, scalable backend systems.

Awesome Lists containing this project

README

          

# FastAPI Authentication Microservice

[![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.104+-green.svg)](https://fastapi.tiangolo.com)
[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-13+-blue.svg)](https://postgresql.org)
[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

A production-ready authentication microservice built with FastAPI, featuring JWT authentication, OAuth2 integration (Google & GitHub), user management, and comprehensive security features.

## ๐Ÿš€ Features

- **๐Ÿ” JWT Authentication** - Secure token-based auth with access & refresh tokens
- **๐ŸŒ OAuth2 Integration** - Google & GitHub OAuth providers
- **๐Ÿ‘ฅ User Management** - Complete CRUD operations with role-based access
- **๐Ÿ›ก๏ธ Security First** - bcrypt password hashing, CORS protection, input validation
- **๐Ÿณ Docker Ready** - Containerized deployment with Docker Compose
- **๐Ÿงช Well Tested** - Comprehensive test suite with 95%+ coverage
- **๐Ÿ“š Auto Docs** - Interactive API documentation with Swagger UI

## ๐Ÿ—๏ธ Architecture

Clean layered architecture following domain-driven design:

```
โ”œโ”€โ”€ app/ # Main application package
โ”‚ โ”œโ”€โ”€ main.py # FastAPI app & lifespan management
โ”‚ โ”œโ”€โ”€ config.py # Environment configuration
โ”‚ โ”œโ”€โ”€ database.py # SQLAlchemy setup
โ”‚ โ”œโ”€โ”€ models/ # Database models
โ”‚ โ”œโ”€โ”€ schemas/ # Pydantic models
โ”‚ โ”œโ”€โ”€ routers/ # API endpoints
โ”‚ โ”œโ”€โ”€ services/ # Business logic
โ”‚ โ””โ”€โ”€ utils/ # Utilities (auth, validation)
โ”œโ”€โ”€ tests/ # Test suite (19 tests, 95%+ coverage)
โ”œโ”€โ”€ alembic/ # Database migrations
โ”œโ”€โ”€ docker-compose.yml # Docker services
โ”œโ”€โ”€ Dockerfile # Container definition
โ”œโ”€โ”€ Makefile # Development commands
โ”œโ”€โ”€ pytest.ini # Test configuration
โ”œโ”€โ”€ requirements.txt # Python dependencies
โ””โ”€โ”€ README.md # This file
```

## ๐Ÿ› ๏ธ Tech Stack

- **Framework**: [FastAPI](https://fastapi.tiangolo.com) - Modern async web framework
- **Database**: [PostgreSQL](https://postgresql.org) with [SQLAlchemy](https://sqlalchemy.org) ORM
- **Auth**: JWT tokens with [python-jose](https://github.com/mpdavis/python-jose)
- **Security**: [bcrypt](https://github.com/pyca/bcrypt) via [passlib](https://passlib.readthedocs.io)
- **OAuth2**: [Authlib](https://authlib.org) for Google & GitHub integration
- **Validation**: [Pydantic](https://pydantic-docs.helpmanual.io) with custom validators
- **Testing**: [pytest](https://pytest.org) with async support
- **Containerization**: [Docker](https://docker.com) & [Docker Compose](https://docs.docker.com/compose)

## ๐Ÿ“‹ Prerequisites

- **Python**: 3.8 or higher
- **Docker & Docker Compose**: For containerized deployment
- **PostgreSQL**: 13+ (for local development)
- **OAuth Credentials**: Google/GitHub (optional, for OAuth features)

## ๐Ÿš€ Quick Start

### ๐Ÿณ Docker (Recommended)

```bash
# Clone repository
git clone https://github.com/samanshafagh/python-fastapi-auth-microservice.git
cd fastapi-auth-microservice

# Copy environment configuration
cp env.example .env

# Start services (app + PostgreSQL + PgAdmin)
docker-compose up -d

# Access the application
# API: http://localhost:8000
# Docs: http://localhost:8000/docs
# PgAdmin: http://localhost:5050
```

### ๐Ÿ’ป Local Development

```bash
# Install dependencies
pip install -r requirements.txt

# Set up PostgreSQL database
createdb auth_db
createuser auth_user

# Configure environment
cp env.example .env
# Edit .env with your database credentials

# Run migrations
alembic upgrade head

# Start development server
uvicorn app.main:app --reload --host 127.0.0.1 --port 8000
```

## โš™๏ธ Configuration

Create a `.env` file from the provided template:

```bash
cp env.example .env
```

### Required Environment Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `DATABASE_URL` | PostgreSQL connection string | `postgresql://user:pass@localhost:5432/auth_db` |
| `SECRET_KEY` | JWT signing secret (use strong random key) | `your-256-bit-secret-key-here` |

### Optional Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `DEBUG` | Debug mode | `true` |
| `ACCESS_TOKEN_EXPIRE_MINUTES` | JWT expiration time | `30` |
| `REFRESH_TOKEN_EXPIRE_DAYS` | Refresh token validity | `7` |
| `CORS_ORIGINS` | Allowed origins (comma-separated) | `http://localhost:3000,http://localhost:8000` |
| `RATE_LIMIT_ENABLED` | Enable rate limiting | `true` |
| `RATE_LIMIT_PER_MINUTE` | General rate limit | `60` |
| `RATE_LIMIT_AUTH_PER_MINUTE` | Auth endpoint rate limit | `5` |

### OAuth2 Configuration (Optional)

```env
# Google OAuth2
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

# GitHub OAuth2
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
```

## ๐Ÿ“– API Documentation

The API is fully documented with interactive Swagger UI:

- **๐Ÿ“š Swagger UI**: http://localhost:8000/docs
- **๐Ÿ“‹ ReDoc**: http://localhost:8000/redoc
- **๐Ÿ” OpenAPI Schema**: http://localhost:8000/openapi.json

### ๐Ÿ”‘ Core Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/api/v1/auth/register` | User registration |
| `POST` | `/api/v1/auth/login` | User authentication |
| `POST` | `/api/v1/auth/refresh` | Refresh access tokens |
| `GET` | `/api/v1/auth/me` | Get current user profile |
| `GET` | `/api/v1/auth/google/login` | Google OAuth login |
| `GET` | `/api/v1/auth/github/login` | GitHub OAuth login |
| `GET` | `/api/v1/users/` | List users (paginated) |
| `GET` | `/api/v1/users/{id}` | Get user by ID |
| `PUT` | `/api/v1/users/{id}` | Update user |
| `DELETE` | `/api/v1/users/{id}` | Delete user |
| `GET` | `/health` | Health check endpoint |

## ๐Ÿ” Security Features

- **JWT Tokens**: Secure token-based authentication
- **Password Hashing**: bcrypt with salt for secure password storage
- **Token Expiration**: Configurable access token expiration
- **Refresh Tokens**: Secure token refresh mechanism
- **CORS Protection**: Configurable Cross-Origin Resource Sharing
- **Input Validation**: Comprehensive request validation with Pydantic
- **Role-Based Access**: Superuser permissions for administrative operations

## ๐Ÿงช Testing & Development

### Run Tests

```bash
# Run all tests
make test

# Run with coverage report
make test-cov

# Run specific test file
pytest tests/test_auth.py -v
```

### Development Commands

```bash
# Install dependencies
make install

# Start development server
make start

# Run database migrations
make migrate

# Create new migration
make migrate-create MESSAGE="add new feature"

# Format code
make format

# Lint code
make lint

# Clean up generated files
make clean
```

## ๐Ÿ—„๏ธ Database Schema

PostgreSQL database with the following tables:

- **`users`** - User accounts with authentication and profile information
- **`refresh_tokens`** - JWT refresh tokens for secure token management
- **`alembic_version`** - Database migration tracking

## ๐Ÿณ Docker Deployment

### Production Setup

1. Update `.env` with production values
2. Set `DEBUG=false` for production
3. Configure production database credentials
4. Update CORS origins for your domain

### Docker Commands

```bash
# Start all services
docker-compose up -d

# View application logs
docker-compose logs -f app

# Rebuild and restart
docker-compose up -d --build

# Stop services
docker-compose down
```

## ๐Ÿ”„ Database Migrations

Uses [Alembic](https://alembic.sqlalchemy.org) for schema migrations:

```bash
# Apply all migrations
alembic upgrade head

# Create new migration
alembic revision --autogenerate -m "add new feature"

# Rollback last migration
alembic downgrade -1

# View migration history
alembic history
```

## ๐Ÿค Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes with tests
4. Ensure all tests pass (`make test`)
5. Submit a Pull Request

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ†˜ Support & Documentation

- ๐Ÿ“– **API Documentation**: http://localhost:8000/docs
- ๐Ÿ› **Bug Reports**: [GitHub Issues](https://github.com/samanshafagh/python-fastapi-auth-microservice/issues)
- ๐Ÿ’ฌ **Discussions**: [GitHub Discussions](https://github.com/samanshafagh/python-fastapi-auth-microservice/discussions)
- ๐Ÿ“ง **Contact**: Create an issue for support questions

## ๐Ÿ™ Acknowledgments

Built with โค๏ธ using [FastAPI](https://fastapi.tiangolo.com), [SQLAlchemy](https://sqlalchemy.org), and other amazing open-source tools.

## ๐Ÿ”ฎ Future Enhancements

- [ ] Email verification for new accounts
- [ ] Password reset functionality
- [ ] Two-factor authentication (2FA)
- [ ] Audit logging for security events
- [ ] Additional OAuth providers (Facebook, Twitter, etc.)
- [ ] GraphQL API support
- [ ] WebSocket support for real-time features
- [ ] Admin dashboard UI