A comprehensive authentication and authorization server built with Flask, designed to be part of a microservice architecture. This service provides centralized user management, authentication, and authorization for other microservices.
This authentication service functions as a central identity provider within a microservice architecture:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Microservice 1 │ │ Microservice 2 │ │ Microservice 3 │
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
│ │ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
└───────────► Auth Microservice ◄───────────┘
└──────────┬──────────┘
│
┌──────────┴──────────┐
│ │
┌────▼─────┐ ┌─────▼────┐
│ Database │ │ Redis │
└──────────┘ └──────────┘
- Flask API: Core application with RESTful endpoints
- PostgreSQL: Primary database for user, role, and permission storage
- Redis: Session tracking and rate limiting
- JWT: Authentication tokens for users and services
- OAuth Integration: Authentication with Google, Microsoft, and Discord
- User registration with email verification
- Login/logout with session tracking
- Password reset functionality
- OAuth 2.0 integration with:
- Microsoft
- Discord
- JWT-based authentication with access and refresh tokens
- Session management (view, delete, limit concurrent sessions)
- Role-based access control (RBAC)
- Permission-based authorization
- Service-specific roles and permissions
- User-service-role assignments
- Application token generation and validation for service-to-service communication
- Service registration and management
- API endpoints for token validation
- Password hashing with bcrypt
- Email verification
- Rate limiting (via Redis)
- Session tracking and management
- Token expiration and refresh
- Active session tracking
- Token usage statistics
- Flask: Web framework
- SQLAlchemy: ORM for database interactions
- PostgreSQL: Primary database
- Redis: Session storage and rate limiting
- JWT: Authentication tokens
- Docker: Containerization
- Authlib: OAuth implementation
- Docker and Docker Compose
- SMTP server for email functionality (or use a service like Mailgun, SendGrid)
- OAuth credentials (for Google, Microsoft, Discord) if using those features
-
Clone the repository:
git clone <repository-url> cd auth_api
-
Copy environment example and configure:
cp .env.example .env # Edit .env with your configuration
-
Start services with Docker Compose:
docker-compose up -d
-
Access the API at http://localhost:5000
The project includes Docker configuration for easy deployment:
# Build and start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop all services
docker-compose down
The project includes comprehensive tests for all components:
# Install test dependencies
pip install -r requirements-dev.txt
# Run all tests
pytest
# Run with coverage report
pytest --cov=app --cov-report=term-missing
We provide a dedicated Dockerfile for testing:
# Run tests using Docker
./run_tests.sh
Or manually:
docker build -t auth-api-tests -f Dockerfile.test .
docker run --rm auth-api-tests
POST /api/auth/register
: Register a new userGET /api/auth/verify-email/<token>
: Verify email addressPOST /api/auth/login
: Authenticate and get tokensPOST /api/auth/logout
: Invalidate current sessionPOST /api/auth/refresh
: Get new access token using refresh tokenGET /api/auth/me
: Get current user profilePOST /api/auth/change-password
: Change password (requires current password)
POST /api/password/forgot
: Request password resetPOST /api/password/reset
: Reset password with token
GET /api/oauth/google
: Initiate Google OAuth flowGET /api/oauth/google/callback
: Google OAuth callbackGET /api/oauth/microsoft
: Initiate Microsoft OAuth flowGET /api/oauth/microsoft/callback
: Microsoft OAuth callbackGET /api/oauth/discord
: Initiate Discord OAuth flowGET /api/oauth/discord/callback
: Discord OAuth callback
GET /api/auth/sessions
: List user's active sessionsDELETE /api/auth/sessions/<session_id>
: Delete specific sessionDELETE /api/auth/sessions
: Delete all sessions except currentGET /api/auth/sessions/stats
: Get session statistics
POST /api/tokens/
: Create new application tokenGET /api/tokens/service/<service_id>
: Get tokens for a servicePOST /api/tokens/<token_id>/revoke
: Revoke a tokenDELETE /api/tokens/<token_id>
: Delete a tokenGET /api/tokens/validate
: Validate an application token
GET /api/roles/user/<user_id>/service/<service_id>
: Get user roles for servicePOST /api/roles/user/<user_id>/service/<service_id>/role/<role_id>
: Assign roleDELETE /api/roles/user/<user_id>/service/<service_id>/role/<role_id>
: Remove rolePOST /api/roles/service/<service_id>
: Create new rolePUT /api/roles/<role_id>
: Update roleDELETE /api/roles/<role_id>
: Delete roleGET /api/roles/service/<service_id>
: Get all roles for serviceGET /api/roles/permissions
: Get all permissions
GET /api/roles/services
: Get all servicesGET /api/roles/services/user
: Get services for current userPOST /api/roles/services
: Create new servicePUT /api/roles/services/<service_id>
: Update serviceDELETE /api/roles/services/<service_id>
: Delete service
The .env
file contains all configuration options. Key settings include:
# Flask configuration
FLASK_APP=app
FLASK_ENV=development
SECRET_KEY=your_secret_key_here
DEBUG=True
# Database configuration
DATABASE_URI=postgresql://postgres:postgres@db:5432/auth_db
# JWT configuration
JWT_SECRET_KEY=your_jwt_secret_key_here
JWT_ACCESS_TOKEN_EXPIRES=3600 # 1 hour
JWT_REFRESH_TOKEN_EXPIRES=2592000 # 30 days
# OAuth configuration
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
# And similar for Microsoft and Discord
# Redis configuration
REDIS_HOST=redis
REDIS_PORT=6379
# Mail configuration
MAIL_SERVER=smtp.example.com
MAIL_PORT=587
MAIL_USE_TLS=True
[email protected]
MAIL_PASSWORD=your_email_password
auth_api/
├── app/ # Application package
│ ├── api/ # API endpoints
│ ├── models/ # Database models
│ ├── services/ # Business logic
│ └── utils/ # Utility functions
├── tests/ # Test suite
├── docker-compose.yml # Docker Compose configuration
├── Dockerfile # Main Dockerfile
├── Dockerfile.test # Dockerfile for testing
└── run.py # Application entry point
- Create/update models in
app/models/
- Implement business logic in
app/services/
- Create API endpoints in
app/api/
- Add tests in
tests/
-
Enhanced Security:
- Implement IP-based rate limiting
- Add CAPTCHA for registration and login attempts
- Add two-factor authentication (2FA)
- Implement device fingerprinting for suspicious login detection
-
Scalability Improvements:
- Add horizontal scaling capabilities with load balancing
- Implement caching for frequently accessed data
- Optimize database queries and indexes
-
Monitoring and Logging:
- Add comprehensive logging with ELK stack integration
- Implement health check endpoints
- Create dashboards for monitoring system health
- Add alerting for suspicious activities
-
Additional Features:
- Support for more OAuth providers (Apple, Facebook, GitHub)
- User profile management
- Account merging for users with multiple OAuth identities
- Organization/team management with hierarchical permissions
- API key management for developers
-
Developer Experience:
- Create SDK libraries for common languages
- Improve API documentation with OpenAPI/Swagger
- Add webhook support for authentication events
- Create admin dashboard UI
This project is licensed under the MIT License - see the LICENSE file for details.
This project includes a custom database migration system that allows you to manage your database schema changes in a controlled way. Migrations are stored as SQL files in the migrations
directory, with separate subdirectories for up
(applying changes) and down
(reverting changes) migrations.
You can use the following commands to manage migrations:
# Create a new migration
./run.py migrate create "migration_name"
# Apply all pending migrations
./run.py migrate up
# Apply a specific number of pending migrations
./run.py migrate up --steps 1
# Revert the most recent migration
./run.py migrate down --steps 1
# Revert all migrations
./run.py migrate down
Migration files are stored in the migrations
directory with the following structure:
migrations/
├── up/
│ ├── 20240309000001-create-users-table.sql
│ ├── 20240309000002-create-services-table.sql
│ └── ...
└── down/
├── 20240309000001-create-users-table.sql
├── 20240309000002-create-services-table.sql
└── ...
Each migration file is prefixed with a timestamp and contains SQL statements to apply or revert the migration. The migration system keeps track of applied migrations in a migrations
table in your database.
When you create a new migration, two files are generated:
- An "up" migration file in
migrations/up/
for applying changes - A "down" migration file in
migrations/down/
for reverting changes
Edit these files to include the SQL statements needed for your schema changes.