Skip to main content

A modular authentication system for FastAPI with OAuth2, JWT, and password recovery

Project description

fastapi-authly

PyPI version Python versions License

A modular authentication system for FastAPI applications. Provides complete user authentication with OAuth2, JWT tokens, password recovery, and more.

โœจ Features

  • ๐Ÿ” OAuth2 Password Flow - Standard OAuth2 authentication
  • ๐ŸŽซ JWT Token Management - Secure token creation and validation
  • ๐Ÿ”‘ Password Recovery - Email-based password reset
  • ๐Ÿ‘ค User Management - Registration, profile management
  • ๐Ÿ“ง Email Verification - User email verification system
  • ๐Ÿ”„ Token Refresh - Refresh token functionality
  • ๐Ÿงฉ Modular Design - Easy to integrate and configure
  • ๐Ÿ›ก๏ธ Security First - Built with security best practices
  • ๐Ÿ“š Type Hints - Full type annotation support

๐Ÿš€ Quick Start (Tortoise + Postgres ้ป˜่ฎคๅฎž็Žฐ)

Installation

uv pip install fastapi-authly
# or
pip install fastapi-authly

Minimal FastAPI App (uses default TortoiseUserRepository)

from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from fastapi_authly import (
    AuthConfig,
    AuthDependencyConfig,
    create_auth_router,
)
from fastapi_authly.contrib.tortoise_pg import TortoiseUserRepository

app = FastAPI()

# 1) init Tortoise (Postgres)
register_tortoise(
    app,
    db_url="postgres://user:password@localhost:5432/mydb",
    modules={"models": ["fastapi_authly.models.user"]},
    generate_schemas=True,
    add_exception_handlers=True,
)

# 2) assemble auth router with default repo (can override via dependencies)
config = AuthConfig(token_url="login")  # keep token_url aligned with /login route
deps = AuthDependencyConfig(user_repository=TortoiseUserRepository())

auth_router = create_auth_router(config=config, dependencies=deps)
app.include_router(auth_router)

Advanced Usage (custom implementations)

from fastapi_authly import AuthConfig, AuthDependencyConfig, create_auth_router
from fastapi_authly.interfaces import UserRepository, Mailer

class MyRepo(UserRepository):
    async def get_by_name(self, username: str): ...
    async def get_by_id(self, user_id: str | int): ...
    async def create_user(self, user): ...
    async def to_public(self, user): ...

class MyMailer(Mailer):
    async def send_password_reset(self, request, token): ...
    async def send_verification(self, email, token): ...

config = AuthConfig(router_prefix="/api/auth", token_url="login")
deps = AuthDependencyConfig(
    user_repository=MyRepo(),
    mailer=MyMailer(),
)
auth_router = create_auth_router(config=config, dependencies=deps)

๐Ÿ“‹ API Endpoints

Authentication

  • POST /auth/login - Login and get access token (+optional refresh)
  • POST /auth/token/verify - Verify token validity
  • POST /auth/token/refresh - Refresh access token

User Management

  • POST /auth/register - User registration
  • GET /auth/me - Get current user info

Password Management

  • POST /auth/password/reset-request - Request password reset
  • POST /auth/password/reset - Reset password with token

๐Ÿ”ง Configuration

AuthConfig Parameters

Parameter Type Default Description
secret_key str "your-secret-key-change-in-production" JWT secret key
algorithm str "HS256" JWT algorithm
access_token_expire_minutes int 30 Access token expiration
refresh_token_expire_days int 7 Refresh token expiration
router_prefix str "/auth" API route prefix
router_tags List[str] ["authentication"] API tags
token_url str "token" OAuth2 token path (set to "login" to match default route)
enable_password_recovery bool True Enable password recovery
enable_user_registration bool True Enable user registration
enable_token_refresh bool True Enable token refresh
enable_html_content bool True Allow HTML in responses
email_from str "noreply@example.com" Email sender
email_from_name str "Auth System" Email sender name
password_reset_url_template str Template URL Password reset URL
verification_url_template str Template URL Email verification URL

๐Ÿ—๏ธ Architecture

fastapi_authly/
โ”œโ”€โ”€ auth.py                    # Main authentication module (routes)
โ”œโ”€โ”€ schemas/                   # Pydantic schemas (request/response models)
โ”‚   โ””โ”€โ”€ user.py
โ”œโ”€โ”€ models/                    # DB models (e.g., Tortoise ORM)
โ”‚   โ””โ”€โ”€ user.py
โ”œโ”€โ”€ contrib/
โ”‚   โ””โ”€โ”€ tortoise_pg.py         # Default Tortoise Postgres repository
โ”œโ”€โ”€ core/                      # Core functionality
โ”‚   โ”œโ”€โ”€ config.py              # Settings & dependency container
โ”‚   โ”œโ”€โ”€ security.py            # Token + password utilities
โ”‚   โ””โ”€โ”€ __init__.py
โ”œโ”€โ”€ interfaces.py              # Protocols (UserRepository, Mailer, etc.)
โ”œโ”€โ”€ __init__.py                # Package exports
โ””โ”€โ”€ __about__.py               # Version info

๐Ÿ”Œ Integration Examples

# FastAPI + Tortoise + Postgres (default repo)
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from fastapi_authly import AuthConfig, AuthDependencyConfig, create_auth_router
from fastapi_authly.contrib.tortoise_pg import TortoiseUserRepository

app = FastAPI()

register_tortoise(
    app,
    db_url="postgres://user:password@localhost:5432/mydb",
    modules={"models": ["fastapi_authly.models.user"]},
    generate_schemas=True,
    add_exception_handlers=True,
)

config = AuthConfig(token_url="login")
deps = AuthDependencyConfig(user_repository=TortoiseUserRepository())
app.include_router(create_auth_router(config=config, dependencies=deps))

๐Ÿงช Testing

# Install test dependencies
uv pip install -e ".[test]"

# Run tests
uv run pytest

๐Ÿ“ฆ Build & Publish

# Build
uv build

# Publish to PyPI (set UV_PUBLISH_TOKEN or pass --token)
uv publish --token pypi-xxxxx

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

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

๐Ÿ“ License

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

๐Ÿ™ Acknowledgments

๐Ÿ“ž Support

If you have any questions or need help:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_authly-0.1.1.tar.gz (166.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_authly-0.1.1-py3-none-any.whl (14.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_authly-0.1.1.tar.gz.

File metadata

  • Download URL: fastapi_authly-0.1.1.tar.gz
  • Upload date:
  • Size: 166.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for fastapi_authly-0.1.1.tar.gz
Algorithm Hash digest
SHA256 700f04e844877213a852ff8a7832b71441d7a75c18825638afc71ebb0afdc2e0
MD5 f4a0c85122a703f240c5ce2aeb8b6a76
BLAKE2b-256 355336eec69a53e1b47849a9689d263dfe01709faa41f33d718026653efbff1c

See more details on using hashes here.

File details

Details for the file fastapi_authly-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: fastapi_authly-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 14.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for fastapi_authly-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8126d0a84924e24d09b06dd37676c9ca47f01416eda89497058ffb3acb38b355
MD5 7ca66d4b0a67fa8ed5cb5b120cb07186
BLAKE2b-256 b531e378e9cf2e893ab7c428b3c6cb3bf40706254f672f373a97a87011c781f4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page