Fast and secure OAuth2 authentication module for FastAPI with email verification
Project description
oauth2fast-fastapi
๐ Fast and secure OAuth2 authentication module for FastAPI with email verification and JWT tokens
[!WARNING] Internal Use Notice
This package is designed and maintained by the Solautyc Team for internal use. While it is publicly available, it may not work as expected in all environments or use cases outside of our specific infrastructure. We do not provide support or guarantees for external usage, and we are not responsible for any issues that may arise from using this package in other contexts.
Use at your own risk. Contributions and feedback are welcome, but compatibility with external environments is not guaranteed.
Features
- ๐ Complete OAuth2 Implementation: Full OAuth2 password flow with JWT tokens
- ๐ง Email Verification: Built-in email verification system with customizable templates
- ๐ค User Management: Ready-to-use user registration, login, and profile endpoints
- ๐๏ธ SQLModel Integration: Async PostgreSQL support with SQLModel/SQLAlchemy
- ๐ Secure Password Hashing: Argon2 password hashing (winner of Password Hashing Competition)
- ๐ฏ FastAPI Dependencies: Easy-to-use dependencies for protected routes
- โก Async/Await: Full async support for high performance
- ๐จ Customizable: Extend the User model with your own fields
- ๐ Type-Safe Configuration: Pydantic settings with environment variables
- ๐ Email Templates: Jinja2 templates for verification and welcome emails
Installation
From PyPI (Recommended)
pip install oauth2fast-fastapi
From Source
# Clone the repository
git clone https://github.com/AngelDanielSanchezCastillo/oauth2fast-fastapi.git
cd oauth2fast-fastapi
# Install in development mode
pip install -e .
# Or install with dev dependencies
pip install -e ".[dev]"
Quick Start
1. Configure Environment Variables
Create a .env file in your project root:
# Required JWT Configuration
SECRET_KEY=your-super-secret-key-change-this-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
# Database Configuration
DB_DEFAULT_CONNECTION=auth
DB_CONNECTIONS__AUTH__HOST=localhost
DB_CONNECTIONS__AUTH__PORT=5432
DB_CONNECTIONS__AUTH__USERNAME=postgres
DB_CONNECTIONS__AUTH__PASSWORD=yourpassword
DB_CONNECTIONS__AUTH__DATABASE=myapp_db
# Mail Server Configuration
MAIL_DEFAULT_ACCOUNT=auth
MAIL_SMTP_ACCOUNTS__AUTH__HOST=smtp.gmail.com
MAIL_SMTP_ACCOUNTS__AUTH__PORT=587
MAIL_SMTP_ACCOUNTS__AUTH__USERNAME="noreply@yourapp.com"
MAIL_SMTP_ACCOUNTS__AUTH__PASSWORD="your-smtp-password"
MAIL_SMTP_ACCOUNTS__AUTH__SECURITY=tls
MAIL_SMTP_ACCOUNTS__AUTH__FROM_EMAIL="noreply@yourapp.com"
MAIL_SMTP_ACCOUNTS__AUTH__FROM_NAME="Your pp"
MAIL_SMTP_ACCOUNTS__AUTH__REPLY_TO="reply@yourapp.com"
MAIL_SMTP_ACCOUNTS__AUTH__TIMEOUT=60
# Application Settings
PROJECT_NAME=My App
FRONTEND_URL=https://yourapp.com
AUTH_URL_PREFIX=auth
[!IMPORTANT] The
SECRET_KEYis required and must be set in your.envfile. Generate a secure key:python -c "import secrets; print(secrets.token_urlsafe(32))"
2. Basic FastAPI Integration
from fastapi import FastAPI, Depends
from oauth2fast_fastapi import router, engine, get_current_user, User
from sqlmodel import SQLModel
app = FastAPI()
# Include authentication router
app.include_router(router, prefix="/auth", tags=["Authentication"])
@app.on_event("startup")
async def startup():
# Create database tables
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
@app.get("/profile")
async def get_profile(current_user: User = Depends(get_current_user)):
return {
"email": current_user.email,
"name": f"{current_user.first_name} {current_user.last_name}",
"verified": current_user.is_verified
}
3. Authentication Flow
Register a new user:
POST /auth/users/register
{
"email": "user@example.com",
"password": "SecurePassword123",
"first_name": "John",
"last_name": "Doe"
}
Verify email:
POST /auth/users/verify-email
{
"token": "verification-token-from-email"
}
Login:
POST /auth/token
Content-Type: application/x-www-form-urlencoded
username=user@example.com&password=SecurePassword123
Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}
Access protected endpoint:
GET /profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Protected Endpoints
Use the provided dependencies to protect your endpoints:
from fastapi import Depends
from oauth2fast_fastapi import get_current_user, get_current_verified_user, User
# Requires authentication only
@app.get("/dashboard")
async def dashboard(user: User = Depends(get_current_user)):
return {"message": f"Welcome {user.email}"}
# Requires authentication AND email verification
@app.get("/premium")
async def premium_feature(user: User = Depends(get_current_verified_user)):
return {"message": "Access granted to verified users only"}
Custom User Model
Extend the base User model with your own fields:
from oauth2fast_fastapi.models.user_model import User as BaseUser
from sqlmodel import Field
class CustomUser(BaseUser, table=True):
__tablename__ = "custom_users"
phone_number: str | None = Field(default=None)
company: str | None = Field(default=None)
role: str = Field(default="user")
Available Endpoints
The authentication router provides the following endpoints:
POST /auth/users/register- Register a new userPOST /auth/users/verify-email- Verify email with tokenPOST /auth/users/resend-verification- Resend verification emailPOST /auth/token- Login and get JWT tokenGET /auth/users/me- Get current user profilePUT /auth/users/me- Update current user profile
Configuration Reference
All configuration is done via environment variables with nested delimiter __.
JWT Settings (Required)
SECRET_KEY- Required: Secret key for JWT signingALGORITHM- Default:"HS256": JWT algorithmACCESS_TOKEN_EXPIRE_MINUTES- Default:60: Token expiration time in minutes
Database Settings
AUTH_DB__USERNAME- Database usernameAUTH_DB__PASSWORD- Database passwordAUTH_DB__HOSTNAME- Database hostAUTH_DB__NAME- Database nameAUTH_DB__PORT- Database port (default: 5432)
Mail Settings
AUTH_MAIL_SERVER__USERNAME- SMTP usernameAUTH_MAIL_SERVER__PASSWORD- SMTP passwordAUTH_MAIL_SERVER__SERVER- SMTP serverAUTH_MAIL_SERVER__PORT- SMTP portAUTH_MAIL_SERVER__FROM_DIRECTION- From email addressAUTH_MAIL_SERVER__FROM_NAME- From nameAUTH_MAIL_SERVER__STARTTLS- Use STARTTLS (default: false)AUTH_MAIL_SERVER__SSL_TLS- Use SSL/TLS (default: true)
Application Settings
PROJECT_NAME- Application name (used in emails)FRONTEND_URL- Frontend URL (for email links)AUTH_URL_PREFIX- Auth router prefix (default: "auth")
๐ Documentation
- Usage Guide - Comprehensive usage guide with examples
- Environment Configuration - All configuration options
๐ Module Structure
oauth2fast-fastapi/
โโโ pyproject.toml
โโโ MANIFEST.in
โโโ README.md
โโโ LICENSE
โโโ src/
โ โโโ oauth2fast_fastapi/
โ โโโ __init__.py
โ โโโ __version__.py
โ โโโ settings.py # Pydantic settings
โ โโโ database.py # Database engine
โ โโโ dependencies.py # FastAPI dependencies
โ โโโ models/
โ โ โโโ bases.py # Base models
โ โ โโโ mixins.py # Model mixins
โ โ โโโ user_model.py # User model
โ โโโ routers/
โ โ โโโ base_router.py # Main router
โ โ โโโ users_router.py # User endpoints
โ โโโ schemas/
โ โ โโโ token_schema.py # JWT schemas
โ โ โโโ user_schema.py # User schemas
โ โ โโโ verification_schema.py
โ โโโ utils/
โ โ โโโ password_utils.py # Password hashing
โ โ โโโ token_utils.py # JWT utilities
โ โ โโโ verification_utils.py
โ โโโ mail/
โ โโโ connection.py # SMTP connection
โ โโโ service.py # Email service
โ โโโ templates/ # Email templates
โ โโโ verification.html
โ โโโ welcome.html
โโโ docs/
โ โโโ env.example
โ โโโ usage.md
โโโ examples/
โ โโโ basic_usage.py
โ โโโ custom_user.py
โ โโโ complete_flow.py
โโโ tests/
Dependencies
This module depends on:
- FastAPI - Modern web framework (MIT License)
- Pydantic - Data validation (MIT License)
- SQLModel - SQL databases with Python (MIT License)
- SQLAlchemy - Database toolkit (MIT License)
- asyncpg - PostgreSQL driver (Apache 2.0)
- python-jose - JWT implementation (MIT License)
- passlib - Password hashing (BSD License)
- fastapi-mail - Email sending (MIT License)
- log2fast-fastapi - Logging module (MIT License)
We are grateful to the maintainers and contributors of these projects.
Security Features
- ๐ Argon2 Password Hashing: Uses Argon2, the winner of the Password Hashing Competition
- ๐ซ JWT Tokens: Secure token-based authentication
- โ๏ธ Email Verification: Prevents fake account creation
- ๐ Secure Defaults: Sensible security defaults out of the box
- ๐ก๏ธ SQL Injection Protection: SQLModel/SQLAlchemy ORM prevents SQL injection
License
This project is licensed under the MIT License - see the LICENSE file for details.
Copyright (c) 2026 Angel Daniel Sanchez Castillo
Note: This package is designed and maintained by the Solautyc Team for internal use. While publicly available under MIT license, use at your own risk.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For issues and questions, please use the GitHub Issues page.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file oauth2fast_fastapi-0.2.5.tar.gz.
File metadata
- Download URL: oauth2fast_fastapi-0.2.5.tar.gz
- Upload date:
- Size: 26.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ca5f9ba7fb204e8a8bac9690869e9b7bbceb4955c7ce585037efe7263753d83b
|
|
| MD5 |
6892fe2593a97e0678022d1d0e5887c3
|
|
| BLAKE2b-256 |
a2a5f3b7fa112871431defb9815720b7f094d3cb4bd2872b1c00b7024f8f3b93
|
File details
Details for the file oauth2fast_fastapi-0.2.5-py3-none-any.whl.
File metadata
- Download URL: oauth2fast_fastapi-0.2.5-py3-none-any.whl
- Upload date:
- Size: 24.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bdd70407ddb0d7ba33d6fc53c998fe314cb1387c71444219b1315958484ac0d4
|
|
| MD5 |
1b5bf1adb824cee4b9f26221afa2fedc
|
|
| BLAKE2b-256 |
ec5d44d908a853a303370a70649e795d2bc7580ea76fc0b6a2810c9328e078d0
|