RESTful API built with FastAPI featuring JWT authentication, HTTP-only cookies, email verification, password recovery, SQLAlchemy ORM, and Alembic migrations.
AuthAPI is a production-ready RESTful authentication API built with FastAPI.
It provides secure session management using JWT stored in HTTP-only cookies, full email-based account validation, password reset flows, and database versioning with Alembic.
This project is designed to be used as a backend foundation for web applications that require secure authentication and session handling.
- 🔐 JWT Authentication
- Access tokens with configurable expiration
- Secure token generation and validation
- 🍪 HTTP-only Cookie Sessions
- Secure against XSS attacks
- SameSite protection
- Configurable TTL
- 📧 Email Account Confirmation
- Token-based email verification
- HTML email templates
- Resend confirmation capability
- 🔁 Password Reset Flow
- One-time reset codes
- Expiration and reuse protection
- 🧠 Authentication Services Layer
- Clear separation between routers, services, and providers
- Modular architecture for easy maintenance
- 🗄️ SQLAlchemy ORM
- MySQL and PostgreSQL support
- Relationship mapping
- 🔄 Alembic Migrations
- Versioned database schema
- Easy rollback capability
- 🔑 Password Hashing
- Bcrypt via Passlib (cost factor 12)
- 📝 Centralized Logging
- Daily log files with rotation
- Comprehensive activity tracking
- 🔒 Local HTTPS Support
- mkcert for secure cookie testing in development
- FastAPI 0.123.9 - Modern, fast web framework
- Uvicorn 0.38.0 - ASGI server
- SQLAlchemy 2.0.44 - SQL toolkit and ORM
- Alembic 1.17.2 - Database migration tool
- PyMySQL 1.1.2 - MySQL driver
- Passlib[bcrypt] 1.7.4 - Password hashing library
- Python-JOSE 3.5.0 - JWT implementation
- FastAPI-Mail 1.6.0 - Email sending service
- Python-Dotenv 1.2.1 - Environment variable management
- Email-Validator 2.3.0 - Email address validation
Before starting, ensure you have:
- Python 3.11+
- pip (Python package manager)
- Git
- MySQL database
- SMTP Email Account (Gmail, SendGrid, etc.)
- mkcert (optional, for local HTTPS)
git clone https://github.com/eliezer-chaves/BaseAPI.git
cd BaseAPIWindows:
python -m venv venvLinux / macOS:
python3 -m venv venvWindows:
venv\Scripts\activateLinux / macOS:
source venv/bin/activatepip install -r requirements.txtCreate a .env file based on .env.example.
MySQL:
DB_NAME=your_database_name
DB_USER=your_database_user
DB_PASSWORD=your_database_password
DB_HOST=localhost
DB_PORT=3306SECRET_KEY=your_jwt_secret_key_here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=15Tip: Generate a strong JWT secret key at JWT Secret Key Generator
AUTH_COOKIE_MAX_AGE=86400
COOKIE_SECRET=your_cookie_secret_key
SHORT_LIVED_TTL_MINUTES=5
⚠️ Important: HTTP-only cookies withSecure=Truerequire HTTPS. This API is designed to run over HTTPS in development and production.
CORS_ORIGINS=https://localhost:4200For multiple origins, use comma separation:
CORS_ORIGINS=https://localhost:4200,https://yourdomain.comMAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password
MAIL_FROM=your_email@gmail.com
MAIL_FROM_NAME=AuthAPI
MAIL_STARTTLS=True
MAIL_SSL_TLS=FalseAPP_NAME=AuthAPI
FRONT_URL=https://localhost:4200Gmail does not allow normal account passwords for SMTP authentication.
-
Enable 2-Step Verification on your Google account
-
Go to App Passwords:
-
Create a new app password:
- Select app: Mail
- Select device: Other (custom name)
- Click "Generate"
-
Use the generated password in your
.env:MAIL_PASSWORD=xxxxxxxxxxxxxxxx
Windows:
- Download from: https://github.com/FiloSottile/mkcert/releases
- Recommended:
mkcert-v1.4.4-windows-amd64.exe - Rename to
mkcert.exeand add to PATH
Linux:
sudo apt install mkcert # Debian/UbuntumacOS:
brew install mkcertmkcert -installNavigate to your project folder and run:
mkcert localhost 127.0.0.1 ::1This will generate:
localhost+2.pem(certificate)localhost+2-key.pem(private key)
uvicorn main:app --reload --host 0.0.0.0 --port 8000 --ssl-certfile localhost+2.pem --ssl-keyfile localhost+2-key.pemAccess:
- API:
https://localhost:8000 - Docs:
https://localhost:8000/docs - ReDoc:
https://localhost:8000/redoc
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 --ssl-certfile /path/to/cert.pem --ssl-keyfile /path/to/key.pemIf you must run over HTTP for testing, modify cookie settings in:
core/handler/cookie_manager.py
Change:
secure=False- Adjust
samesiteparameter
Note: This is only for local testing. In production, always use HTTPS.
Run after configuring .env:
alembic upgrade headThis creates:
usr_userstable (user accounts)email_confirmation_tokenstable (email verification)password_reset_codestable (password recovery)
alembic revision -m "migration description"alembic downgrade -1alembic historyPOST /auth/sessions/login- User loginPOST /auth/sessions/logout- User logoutGET /auth/sessions/validate- Validate current session
POST /auth/accounts/register- Create new accountPOST /auth/accounts/confirm- Confirm email with tokenPOST /auth/accounts/resend-confirmation- Resend confirmation email
POST /auth/password-resets/request- Request password reset codePOST /auth/password-resets/validate- Validate reset codePOST /auth/password-resets/reset- Reset password with code
BaseAPI/
├── alembic/ # Database migrations
│ ├── versions/ # Migration version files
│ │ ├── f5dbc96d3811_create_usr_users_table.py
│ │ ├── 0c4f9a65af1b_email_confirmation_token_table.py
│ │ └── 2cf037885739_create_password_reset_codes_table.py
│ ├── env.py
│ └── script.py.mako
├── core/ # Core application logic
│ ├── config/ # Configuration files
│ │ └── email_config.py # Email service configuration
│ ├── handler/ # Request/Response handlers
│ │ └── cookie_manager.py # HTTP-only cookie management
│ ├── providers/ # Security providers
│ │ ├── hash_provider.py # Password hashing with bcrypt
│ │ └── jwt_provider.py # JWT token generation/validation
│ ├── services/ # Business logic services
│ │ ├── auth/ # Authentication services
│ │ │ ├── auth_service.py # Login/logout logic
│ │ │ └── password_reset_service.py # Password reset flow
│ │ └── email_service.py # Email sending service
│ ├── templates/ # HTML email templates
│ │ ├── confirm_account.html # Account confirmation email
│ │ └── reset_password.html # Password reset email
│ └── utils/ # Utility functions
│ └── email_utils.py # Email helpers
├── logs/ # Application logs (daily rotation)
│ └── YYYY-MM-DD.log # Daily log files
├── models/ # SQLAlchemy models
│ └── auth_models/ # Authentication models
│ ├── user_model.py # User account model
│ ├── email_tokens_model.py # Email verification tokens
│ ├── password_reset_code_model.py # Password reset codes
│ └── __init__.py
├── routers/ # API route handlers
│ └── auth/ # Authentication routes
│ ├── sessions_router.py # Login/logout endpoints
│ ├── accounts_router.py # Registration/verification
│ └── password_resets_router.py # Password reset endpoints
├── schemas/ # Pydantic validation schemas
│ └── user_schema.py # User request/response schemas
├── .env # Environment variables (not in git)
├── .env.example # Environment variables template
├── .gitignore # Git ignore rules
├── alembic.ini # Alembic configuration
├── database.py # Database connection setup
├── logging_config.py # Logging configuration
├── main.py # Application entry point
├── requirements.txt # Python dependencies
└── README.md # This file
Once the server is running, access the interactive documentation:
- Swagger UI:
https://localhost:8000/docs - ReDoc:
https://localhost:8000/redoc
Both provide complete API documentation with request/response examples and the ability to test endpoints directly from your browser.
- ✅ HTTP-only cookies prevent XSS attacks
- ✅ CORS configuration limits allowed origins
- ✅ JWT tokens with configurable expiration
- ✅ Bcrypt password hashing (cost factor 12)
- ✅ Email verification prevents fake accounts
- ✅ Rate limiting on email sending
- ✅ Secure password reset flow with time-limited codes
- ✅ SQL injection protection via SQLAlchemy ORM
- ✅ SameSite cookie protection
- Verify database credentials in
.env - Ensure database server is running
- Check that database exists (
DB_NAME) - Test connection manually
- Verify SMTP credentials
- For Gmail, use App Password, not regular password
- Check firewall/antivirus blocking port 587
- Test SMTP connection separately
- Re-run
mkcert -install - Regenerate certificates:
mkcert localhost 127.0.0.1 ::1 - Clear browser cache and restart browser
- Ensure virtual environment is activated
- Re-install dependencies:
pip install -r requirements.txt - Check Python version (3.11+ required)
- Ensure HTTPS is enabled (cookies with
Secure=Truerequire HTTPS) - Check CORS_ORIGINS matches your frontend URL
- Verify browser allows third-party cookies
This backend is designed to work with a frontend application.
BaseFrontAngular: https://github.com/eliezer-chaves/BaseFrontAngular
The frontend includes:
- Login/Registration forms
- Email verification flow
- Password reset functionality
- Protected routes with JWT authentication
- HTTP-only cookie handling
Make sure the backend is running before starting the frontend application.
This project is for personal and educational use.
Developed by Eliézer Chaves
- GitHub: @eliezer-chaves
⭐ If this project helped you, consider starring the repository!
💻 Built with security, caffeine, and FastAPI ❤️