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.
- Host: GitHub
- URL: https://github.com/samanshafagh/python-fastapi-auth-microservice
- Owner: samanshafagh
- Created: 2025-12-22T13:21:48.000Z (about 1 month ago)
- Default Branch: main
- Last Pushed: 2025-12-22T13:45:04.000Z (about 1 month ago)
- Last Synced: 2025-12-24T00:32:27.022Z (about 1 month ago)
- Topics: api-security, backend, docker, fastapi, jwt, microservice, oauth2, postgresql, pytest, python, sqlalchemy
- Language: Python
- Homepage:
- Size: 29.3 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# FastAPI Authentication Microservice
[](https://python.org)
[](https://fastapi.tiangolo.com)
[](https://postgresql.org)
[](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