
๐ A production-ready authentication system built with FastAPI
Features โข Screenshots โข Quick Start โข API Docs โข Deploy โข Contributing
- ๐ JWT Authentication - Secure token-based authentication with access and refresh tokens
- ๐ Token Refresh - Automatic token refresh mechanism
- ๐ง Email Verification - Email-based account verification
- ๐ Password Reset - Secure password reset via email
- ๐ก๏ธ Two-Factor Authentication (2FA) - TOTP-based 2FA with QR codes
- ๐ฑ Device Management - Track and manage logged-in devices
- ๐ Login History - Monitor login attempts and locations
- โก Rate Limiting - Protect against brute force attacks
- ๐ OAuth2 Integration - Support for multiple providers
- ๐ Google Login - Sign in with Google account
- ๐ GitHub Login - Sign in with GitHub account
- ๐ค User Profiles - Customizable user profiles with avatars
- ๐จโ๐ผ Admin Panel - User management for administrators
- ๐ธ Avatar Upload - Profile picture upload with image processing
- ๐จ Beautiful Dashboard - Modern, responsive design
- ๐ฑ Mobile Friendly - Fully responsive on all devices
- ๐ Clean Interface - Intuitive and user-friendly
- Python 3.8+ (Recommended: 3.11)
- MySQL 8.0+ (optional, SQLite by default)
- SMTP server (optional, for email features)
- Docker & Docker Compose (optional, for containerized deployment)
# Fork this repository on GitHub first, then clone your fork
git clone https://github.com/Evil0ctal/fastapi-jwt-auth.git
cd fastapi-jwt-auth
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Create .env file from example
cp .env.example .env
# Edit .env file with your settings
# For quick start, the default settings work out of the box!
# Run database initialization
python init_db.py
# This will:
# - Create all database tables
# - Create a demo user (if APP_MODE=demo)
# - Optionally create a superuser account
# Start the application
python run.py
# Or use uvicorn directly
uvicorn app.main:app --reload --port 8000
Open your browser and navigate to:
- ๐ Application: http://localhost:8000
- ๐ API Docs: http://localhost:8000/docs
- ๐ง ReDoc: http://localhost:8000/redoc
Demo Credentials (if APP_MODE=demo):
- Email:
demo@example.com
- Password:
demo123
fastapi-jwt-auth/
โโโ app/ # Application core
โ โโโ api/ # API endpoints
โ โ โโโ auth.py # Authentication endpoints
โ โ โโโ users.py # User management endpoints
โ โ โโโ oauth.py # OAuth2 endpoints
โ โ โโโ two_factor_auth.py # 2FA endpoints
โ โ โโโ devices.py # Device management endpoints
โ โโโ core/ # Core functionality
โ โ โโโ config.py # Configuration settings
โ โ โโโ security.py # Security utilities
โ โ โโโ logging.py # Logging configuration
โ โ โโโ rate_limit.py # Rate limiting
โ โโโ db/ # Database
โ โ โโโ base.py # Database base classes
โ โ โโโ database.py # Database connection
โ โโโ models/ # SQLAlchemy models
โ โ โโโ user.py # User model
โ โ โโโ oauth_account.py # OAuth accounts
โ โ โโโ two_factor_auth.py # 2FA model
โ โ โโโ ... # Other models
โ โโโ schemas/ # Pydantic schemas
โ โ โโโ user.py # User schemas
โ โ โโโ token.py # Token schemas
โ โ โโโ ... # Other schemas
โ โโโ services/ # Business logic
โ โ โโโ user.py # User service
โ โ โโโ email.py # Email service
โ โ โโโ oauth.py # OAuth service
โ โ โโโ ... # Other services
โ โโโ templates/ # Email templates
โ โ โโโ emails/ # HTML email templates
โ โโโ main.py # Application entry point
โโโ static/ # Frontend files
โ โโโ css/ # Stylesheets
โ โโโ js/ # JavaScript files
โ โโโ images/ # Images
โ โโโ dashboard.html # Main dashboard
โ โโโ login.html # Login page
โ โโโ ... # Other pages
โโโ tests/ # Test files
โโโ .env.example # Environment example
โโโ requirements.txt # Python dependencies
โโโ run.py # Application runner
โโโ init_db.py # Database initialization
- Create a New API Endpoint
# app/api/your_feature.py
from fastapi import APIRouter, Depends
from app.api.deps import get_current_user
router = APIRouter()
@router.get("/your-endpoint")
async def your_endpoint(current_user = Depends(get_current_user)):
# Your logic here
return {"message": "Hello from your endpoint"}
- Register the Router
# app/main.py
from app.api import your_feature
app.include_router(
your_feature.router,
prefix="/api/v1/your-feature",
tags=["your-feature"]
)
- Add Frontend Page
Create a new section in dashboard.html
:
// Add to navigation
<li>
<a class="nav-link" data-section="your-section">
<span class="nav-icon">๐ฏ</span>
<span>Your Feature</span>
</a>
</li>
// Add section content
<section id="your-section" class="section">
<!-- Your content here -->
</section>
- Colors and Theme
Edit CSS variables in dashboard.html
:
:root {
--primary-color: #3b82f6; /* Change primary color */
--dark-bg: #0f172a; /* Change sidebar color */
/* ... other variables ... */
}
- Adding Dashboard Widgets
Add new stat cards in the overview section:
<div class="stat-card">
<div class="stat-icon primary">๐</div>
<div class="stat-value">42</div>
<div class="stat-label">Your Metric</div>
</div>
- Create a New Model
# app/models/your_model.py
from sqlalchemy import Column, Integer, String, ForeignKey
from app.db.base import Base
class YourModel(Base):
__tablename__ = "your_table"
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
user_id = Column(Integer, ForeignKey("users.id"))
- Create Pydantic Schema
# app/schemas/your_schema.py
from pydantic import BaseModel
class YourModelCreate(BaseModel):
name: str
class YourModelResponse(BaseModel):
id: int
name: str
class Config:
from_attributes = True
User Registration โ Email Verification โ Login โ JWT Token โ Access Protected Routes
โ
Refresh Token โ New Access Token
- User: Core user information
- RefreshToken: JWT refresh tokens
- UserDevice: Trusted devices
- LoginHistory: Login attempts
- TwoFactorAuth: 2FA settings
- OAuthAccount: Social login connections
- Password hashing with bcrypt
- JWT tokens with expiration
- Rate limiting per IP/user
- Device fingerprinting
- Optional 2FA verification
- Colors and Theme
Edit CSS variables in dashboard.html
:
:root {
--primary-color: #3b82f6; /* Change primary color */
--dark-bg: #0f172a; /* Change sidebar color */
/* ... other variables ... */
}
- Adding Dashboard Widgets
Add new stat cards in the overview section:
<div class="stat-card">
<div class="stat-icon primary">๐</div>
<div class="stat-value">42</div>
<div class="stat-label">Your Metric</div>
</div>
- Create a New Model
# app/models/your_model.py
from sqlalchemy import Column, Integer, String, ForeignKey
from app.db.base import Base
class YourModel(Base):
__tablename__ = "your_table"
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
user_id = Column(Integer, ForeignKey("users.id"))
- Create Pydantic Schema
# app/schemas/your_schema.py
from pydantic import BaseModel
class YourModelCreate(BaseModel):
name: str
class YourModelResponse(BaseModel):
id: int
name: str
class Config:
from_attributes = True
Variable | Description | Default |
---|---|---|
APP_MODE |
Application mode (demo/production) | demo |
SECRET_KEY |
JWT secret key | change-in-production |
DATABASE_URL |
Database connection URL | sqlite:///./app.db |
DATABASE_TYPE |
Database type (sqlite/mysql) | sqlite |
EMAIL_ENABLED |
Enable email features | false |
RATE_LIMIT_ENABLED |
Enable rate limiting | true |
GOOGLE_CLIENT_ID |
Google OAuth client ID | "" |
GOOGLE_CLIENT_SECRET |
Google OAuth secret | "" |
GITHUB_CLIENT_ID |
GitHub OAuth client ID | "" |
GITHUB_CLIENT_SECRET |
GitHub OAuth secret | "" |
See .env.example
for all configuration options.
-
Google OAuth
- Create project at Google Cloud Console
- Enable Google+ API
- Create OAuth2 credentials
- Add redirect URI:
http://localhost:8000/api/v1/oauth/callback/google
-
GitHub OAuth
- Go to GitHub Settings > Developer settings > OAuth Apps
- Create new OAuth App
- Add authorization callback:
http://localhost:8000/api/v1/oauth/callback/github
Method | Endpoint | Description |
---|---|---|
POST | /api/v1/auth/register |
Register new user |
POST | /api/v1/auth/login |
Login user |
POST | /api/v1/auth/logout |
Logout user |
POST | /api/v1/auth/refresh |
Refresh access token |
POST | /api/v1/auth/forgot-password |
Request password reset |
POST | /api/v1/auth/reset-password |
Reset password |
POST | /api/v1/auth/verify-email |
Verify email address |
Method | Endpoint | Description |
---|---|---|
GET | /api/v1/users/me |
Get current user |
PUT | /api/v1/users/me |
Update current user |
POST | /api/v1/users/me/avatar |
Upload avatar |
DELETE | /api/v1/users/me/avatar |
Delete avatar |
PUT | /api/v1/users/me/password |
Change password |
GET | /api/v1/users/ |
List all users (admin) |
Method | Endpoint | Description |
---|---|---|
GET | /api/v1/2fa/status |
Get 2FA status |
POST | /api/v1/2fa/setup |
Setup 2FA |
POST | /api/v1/2fa/verify |
Verify 2FA code |
DELETE | /api/v1/2fa/disable |
Disable 2FA |
GET | /api/v1/devices/ |
List user devices |
DELETE | /api/v1/devices/{device_id} |
Remove device |
GET | /api/v1/devices/login-history |
Get login history |
See full API documentation at /docs
when running the application.
# Run all tests
python run_tests.py
# Run specific test file
python run_tests.py test_auth.py
# Run with coverage
python run_tests.py --coverage
# Run tests by module
python run_tests.py --modules
# Clone the repository
git clone https://github.com/Evil0ctal/fastapi-jwt-auth.git
cd fastapi-jwt-auth
# Copy environment file
cp .env.example .env
# Start services
docker-compose up -d
# Initialize database (first time only)
docker-compose exec app python init_db.py
The application will be available at:
- Application: http://localhost:8000
- API Docs: http://localhost:8000/docs
# Use production profile with Nginx
docker-compose --profile production up -d
This will start:
- FastAPI application on port 8000
- MySQL database on port 3306
- Nginx reverse proxy on port 80
-
Security
- Change
SECRET_KEY
to a strong random value - Enable HTTPS with SSL certificates (Let's Encrypt)
- Configure CORS origins properly
- Review and adjust rate limiting settings
- Change
-
Database
- Use MySQL or PostgreSQL instead of SQLite
- Set up regular automated backups
- Configure connection pooling
-
Monitoring
- Set up application monitoring (Prometheus/Grafana)
- Configure centralized logging (ELK stack)
- Set up error tracking (Sentry)
-
Performance
- Enable Redis for caching
- Configure CDN for static assets
- Set up horizontal scaling with load balancer
-
Port Already in Use
- The application automatically tries port 8001 if 8000 is occupied
- Or manually change the port in
run.py
or docker-compose.yml
-
Database Connection Issues
- Ensure MySQL service is running if using MySQL
- Check database credentials in
.env
file - For Docker, wait for MySQL to be fully initialized
-
Email Not Sending
- Verify SMTP settings in
.env
- For Gmail, use App Passwords instead of regular password
- Check if
EMAIL_ENABLED=true
- Verify SMTP settings in
-
OAuth Login Not Working
- Verify OAuth credentials are correctly set
- Ensure callback URLs match your domain
- Check if frontend URL is correctly configured
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature
) - Commit your changes (
git commit -m 'Add some AmazingFeature'
) - Push to the branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
# Install in development mode
pip install -r requirements.txt
# Run tests
python run_tests.py
# Run with auto-reload
uvicorn app.main:app --reload
This project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI - The awesome web framework
- SQLAlchemy - The database toolkit
- Pydantic - Data validation library
- All contributors who helped build this project
This project implements several security best practices:
- ๐ Password Security: Bcrypt hashing with salt rounds
- ๐๏ธ JWT Tokens: Short-lived access tokens with refresh rotation
- ๐ Token Rotation: Automatic refresh token rotation
- ๐ซ Rate Limiting: Protection against brute force attacks
- โ Input Validation: Pydantic models for data validation
- ๐พ SQL Injection Protection: SQLAlchemy ORM with parameterized queries
- ๐ XSS Protection: Template sanitization and CSP headers
- ๐ CORS: Configurable cross-origin resource sharing
- ๐ 2FA Support: TOTP-based two-factor authentication
For security concerns, please email: evil0ctal1985@gmail.com
- Async/await throughout for optimal performance
- Connection pooling for database
- Lazy loading of relationships
- Optimized queries with proper indexing
- Static file caching with proper headers
- Multi-stage Docker builds for smaller images
- ๐ Documentation
- ๐ Issue Tracker
- ๐ฌ Discussions
- ๐ง Email: evil0ctal1985@gmail.com
If you find this project useful, please consider giving it a โญ!
Made with โค๏ธ using FastAPI