Skip to main content

A simple and robust OTP (One-Time Password) authentication library for FastAPI, backed by Redis and Email.

Project description

FastAPI OTP Auth

PyPI version License: MIT

A simple and robust OTP (One-Time Password) authentication library for FastAPI, backed by Redis and Email.

Features

  • 🔐 Secure OTP Generation: Cryptographically secure 6-digit codes.
  • 🎫 JWT Support: Auto-generates Access and Refresh tokens upon verification.
  • 🍪 HttpOnly Cookies: Securely stores refresh tokens in HttpOnly cookies.
  • Redis-Backed: Fast and reliable storage for OTPs with automatic expiration.
  • 📧 Email Delivery: Integrated email sending using fastapi-mail.
  • 🔌 Easy Integration: Drop-in APIRouter for quick setup.
  • ⚙️ Configurable: Fully customizable via environment variables.
  • 🚫 Token Blacklisting: Secure logout and immediate token revocation.

Installation

pip install fastapi-otp-auth

Or using Poetry:

poetry add fastapi-otp-auth

Configuration

The library is configured using environment variables. The prefix for all variables is FASTAPI_OTP_AUTH_.

Variable Description Default
FASTAPI_OTP_AUTH_REDIS_URL Connection string for Redis redis://localhost:6379/0
FASTAPI_OTP_AUTH_SMTP_SERVER SMTP server hostname 127.0.0.1
FASTAPI_OTP_AUTH_SMTP_PORT SMTP server port 1025
FASTAPI_OTP_AUTH_SMTP_USERNAME SMTP username user@example.com
FASTAPI_OTP_AUTH_SMTP_PASSWORD SMTP password password
FASTAPI_OTP_AUTH_MAIL_FROM_NAME Sender name for emails FastAPI App
FASTAPI_OTP_AUTH_OTP_EXPIRY_SECONDS OTP validity duration in seconds 300 (5 minutes)
FASTAPI_OTP_AUTH_OTP_KEY_PREFIX Prefix for Redis keys otp_
FASTAPI_OTP_AUTH_JWT_SECRET Secret key for signing JWTs change-me-in-production
FASTAPI_OTP_AUTH_JWT_ALGORITHM Algorithm for JWTs HS256
FASTAPI_OTP_AUTH_ACCESS_TOKEN_EXPIRE_MINUTES Access token lifetime 60 (1 hour)
FASTAPI_OTP_AUTH_REFRESH_TOKEN_EXPIRE_DAYS Refresh token lifetime 7 (7 days)
FASTAPI_OTP_AUTH_BLACKLIST_KEY_PREFIX Prefix for blacklisted tokens in Redis blacklist_

Usage

Import the auth_router and include it in your FastAPI application:

from fastapi import FastAPI
from fastapi_otp_auth.auth_router import router as auth_router

app = FastAPI()

# Include the router
app.include_router(auth_router, prefix="/auth", tags=["Authentication"])

# The following endpoints will be available:
# POST /auth/request-otp - Request a new OTP
# POST /auth/verify-otp  - Verify a received OTP
# POST /auth/logout      - Logout and blacklist tokens

Requesting an OTP

Send a POST request to /auth/request-otp:

{
  "email": "user@example.com"
}

Verifying an OTP

Send a POST request to /auth/verify-otp:

{
  "email": "user@example.com",
  "otp": "123456"
}

On success, the response will contain the access token, and the refresh token will be set as an HttpOnly cookie:

{
  "message": "OTP verified successfully!",
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer"
}

Protecting Routes

Use the get_current_user dependency to protect routes. This will verify the access token and return the user's email.

from fastapi import Depends
from fastapi_otp_auth.dependencies import get_current_user

@app.get("/protected")
async def protected_route(user: str = Depends(get_current_user)):
    return {"message": f"Hello, {user}!"}

Refreshing Tokens

To get a new access token using the HttpOnly refresh token cookie, send a POST request to /auth/refresh. The browser will automatically include the cookie.

POST /auth/refresh

Response:

{
  "access_token": "new_access_token_here",
  "token_type": "bearer"
}

### Logging Out

To logout, send a POST request to `/auth/logout`. This will blacklist both the access token (provided in the Authorization header) and the refresh token (provided in the cookie).

```bash
POST /auth/logout
Authorization: Bearer <access_token>
Cookie: refresh_token=<refresh_token>

Response:

{
  "message": "Successfully logged out"
}

Development

To run tests locally using Docker (no local environment needed):

make test

This will spin up a Redis container and run the test suite in an isolated environment.

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_otp_auth-0.1.0.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

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

fastapi_otp_auth-0.1.0-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_otp_auth-0.1.0.tar.gz.

File metadata

  • Download URL: fastapi_otp_auth-0.1.0.tar.gz
  • Upload date:
  • Size: 6.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.9 Linux/6.11.0-1018-azure

File hashes

Hashes for fastapi_otp_auth-0.1.0.tar.gz
Algorithm Hash digest
SHA256 e77ded7615be3284f8bdff18379c383060d48d70415d1ea2a1a43a3adb672a2b
MD5 8e5da31de21b27d2bd2b086d77b41c46
BLAKE2b-256 1e82f382b3ad96c561895087bdafacfc3fa97f416bb1dbc6a8881a634d0f5f45

See more details on using hashes here.

File details

Details for the file fastapi_otp_auth-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_otp_auth-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 9.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.9 Linux/6.11.0-1018-azure

File hashes

Hashes for fastapi_otp_auth-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c56e5ccb3d438261eaafd5f2367eb2400705d0dab8462ee6fc84b0e574e86d78
MD5 8046b05bcd36c26b04b48976d1c7eb14
BLAKE2b-256 8c56e7c9e23518941a93a1f79f9b8277a182c86dcbcc09f2ccc61e9a8ac2b2f7

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