Skip to content

Evil0ctal/FastAPI-JWT-Auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

8 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

FastAPI JWT Auth System

FastAPI JWT Auth

๐Ÿ” Modern Authentication System for FastAPI Applications

Python FastAPI SQLAlchemy JWT License

Docker MySQL Redis Swagger

Code Style Security Async Test

GitHub Stars GitHub Forks GitHub Issues GitHub Pull Requests

๐Ÿš€ A production-ready authentication system built with FastAPI

Features โ€ข Screenshots โ€ข Quick Start โ€ข API Docs โ€ข Deploy โ€ข Contributing


๐Ÿ› ๏ธ Technologies & Tools

FastAPI Python MySQL SQLite Docker JWT

SQLAlchemy Pydantic Uvicorn Pytest Swagger GitHub


๐Ÿ“ธ Screenshots

Login Page Dashboard
Profile Page Security Settings

โœจ Features

Core Authentication

  • ๐Ÿ” 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

Advanced Security

  • ๐Ÿ›ก๏ธ 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

Social Login

  • ๐ŸŒ OAuth2 Integration - Support for multiple providers
  • ๐Ÿ”— Google Login - Sign in with Google account
  • ๐Ÿ™ GitHub Login - Sign in with GitHub account

User Management

  • ๐Ÿ‘ค User Profiles - Customizable user profiles with avatars
  • ๐Ÿ‘จโ€๐Ÿ’ผ Admin Panel - User management for administrators
  • ๐Ÿ“ธ Avatar Upload - Profile picture upload with image processing

Modern UI/UX

  • ๐ŸŽจ Beautiful Dashboard - Modern, responsive design
  • ๐Ÿ“ฑ Mobile Friendly - Fully responsive on all devices
  • ๐ŸŒ“ Clean Interface - Intuitive and user-friendly

๐Ÿš€ Quick Start

Prerequisites

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

1. Fork and Clone

# 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

2. Configure Environment

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

3. Initialize Database

# 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

4. Run the Application

# Start the application
python run.py

# Or use uvicorn directly
uvicorn app.main:app --reload --port 8000

5. Access the Application

Open your browser and navigate to:

Demo Credentials (if APP_MODE=demo):

  • Email: demo@example.com
  • Password: demo123

๐Ÿ“ Project Structure

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

๐Ÿ› ๏ธ Development Guide

Adding New Features

  1. 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"}
  1. 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"]
)
  1. 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>

Customizing the UI

  1. Colors and Theme

Edit CSS variables in dashboard.html:

:root {
    --primary-color: #3b82f6;  /* Change primary color */
    --dark-bg: #0f172a;        /* Change sidebar color */
    /* ... other variables ... */
}
  1. 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>

Database Models

  1. 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"))
  1. 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

Component Design

1. Authentication Flow

User Registration โ†’ Email Verification โ†’ Login โ†’ JWT Token โ†’ Access Protected Routes
                                           โ†“
                                    Refresh Token โ†’ New Access Token

2. Database Models

  • User: Core user information
  • RefreshToken: JWT refresh tokens
  • UserDevice: Trusted devices
  • LoginHistory: Login attempts
  • TwoFactorAuth: 2FA settings
  • OAuthAccount: Social login connections

3. Security Layers

  • Password hashing with bcrypt
  • JWT tokens with expiration
  • Rate limiting per IP/user
  • Device fingerprinting
  • Optional 2FA verification

Customizing the UI

  1. Colors and Theme

Edit CSS variables in dashboard.html:

:root {
    --primary-color: #3b82f6;  /* Change primary color */
    --dark-bg: #0f172a;        /* Change sidebar color */
    /* ... other variables ... */
}
  1. 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>

Database Models

  1. 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"))
  1. 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

๐Ÿ”ง Configuration

Environment Variables

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.

OAuth2 Setup

  1. 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
  2. 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

๐Ÿ“ฆ API Documentation

Authentication Endpoints

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

User Endpoints

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)

Security Endpoints

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.

๐Ÿงช Testing

# 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

๐Ÿš€ Deployment

Docker Deployment

Quick Start with Docker Compose

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

Production Deployment

# 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

Production Checklist

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

๐Ÿ› Known Issues & Troubleshooting

Common Issues

  1. 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
  2. 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
  3. Email Not Sending

    • Verify SMTP settings in .env
    • For Gmail, use App Passwords instead of regular password
    • Check if EMAIL_ENABLED=true
  4. OAuth Login Not Working

    • Verify OAuth credentials are correctly set
    • Ensure callback URLs match your domain
    • Check if frontend URL is correctly configured

๐Ÿค Contributing

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

Development Setup

# Install in development mode
pip install -r requirements.txt

# Run tests
python run_tests.py

# Run with auto-reload
uvicorn app.main:app --reload

๐Ÿ“„ License

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

๐Ÿ™ Acknowledgments

  • FastAPI - The awesome web framework
  • SQLAlchemy - The database toolkit
  • Pydantic - Data validation library
  • All contributors who helped build this project

๐Ÿ”’ Security

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

๐Ÿ“ˆ Performance

  • 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

๐Ÿ“ž Support


If you find this project useful, please consider giving it a โญ!

Made with โค๏ธ using FastAPI

Report Bug โ€ข Request Feature

About

๐Ÿ” FastAPI JWT่ฎค่ฏๆจกๆฟ (FastAPI JWT Authentication Template)

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  • ย 
  • ย