FastAPI-Auth-JWT is a ready-to-use and easy-to-customize authentication middleware for FastAPI.
Project description
FastAPI Auth JWT
Seamless, production-ready JWT authentication for your FastAPI applications.
| Source Code | Documentation | Live Demos |
|---|---|---|
| GitHub | Docs | Examples |
Table of Contents
- 🌟 Why FastAPI Auth JWT?
- 📦 Installation
- 🚀 Getting Started
- 🧰 Redis Extension
- ⚙️ Key Components & Configurations
- 📂 Example Projects
- 📚 Documentation
- 🛡️ License
- ⭐ Get Involved
🌟 Why FastAPI Auth JWT?
FastAPI Auth JWT empowers developers to implement secure, reliable, and efficient JWT-based authentication in their FastAPI applications. With minimal setup and deep customization options, it helps projects of all sizes establish trust, protect sensitive endpoints, and scale seamlessly.
- 🚀 Quick Setup: Integrate JWT authentication into new or existing FastAPI projects in just a few lines.
- 🛠️ Configurable & Extensible: Easily adapt authentication rules, user schemas, and token lifetimes to meet dynamic requirements.
- 🔄 Sync & Async Compatible: Whether your routes are synchronous or asynchronous, the middleware and backend integrate smoothly.
- 💾 Multiple Storage Backends: Start with in-memory caching for simplicity, then scale transparently to Redis for high-availability, distributed architectures.
- ✅ Thoroughly Tested & Documented: A well-structured codebase with comprehensive tests and clear documentation means you can rely on stable, predictable behavior.
📦 Installation
Basic Installation:
pip install fastapi-auth-jwt
With Redis Support:
pip install fastapi-auth-jwt[redis]
From Source:
- Clone the repository:
git clone https://github.com/deepmancer/fastapi-auth-jwt.git
- Navigate to the directory:
cd fastapi-auth-jwt
- Install the package:
pip install .
Requirements:
- Python 3.8+
- FastAPI 0.65.2+
🚀 Getting Started
Below is a high-level example to get you started. For more advanced use cases and patterns, refer to the examples section and the official docs.
🛠️ 1. Define a User Model
Create a simple Pydantic model representing your user entity.
from pydantic import BaseModel, Field
from typing import Optional
class User(BaseModel):
username: str
password: str
token: Optional[str] = Field(None)
⚙️ 2. Configure Authentication Settings
Specify your JWT signing secrets, algorithms, and token expiration times.
from pydantic import BaseModel
class AuthenticationSettings(BaseModel):
secret: str = "your-secret-key"
jwt_algorithm: str = "HS256"
expiration_seconds: int = 3600 # 1 hour
🔧 3. Initialize the Authentication Backend
Integrate the JWTAuthBackend using your settings and user schema.
from fastapi_auth_jwt import JWTAuthBackend
auth_backend = JWTAuthBackend(
authentication_config=AuthenticationSettings(),
user_schema=User
)
🔌 4. Add Middleware to FastAPI
Hook the authentication middleware into your application.
from fastapi import FastAPI
from fastapi_auth_jwt import JWTAuthenticationMiddleware
app = FastAPI()
app.add_middleware(
JWTAuthenticationMiddleware,
backend=auth_backend,
exclude_urls=["/sign-up", "/login"], # Public endpoints
)
📚 5. Define Your Routes
Secure routes automatically validate tokens before accessing the request state.
@app.post("/sign-up")
async def sign_up(user: User):
# Implement user creation logic here
return {"message": "User created"}
@app.post("/login")
async def login(user: User):
token = await auth_backend.create_token(
{"username": user.username, "password": user.password},
expiration=3600
)
return {"token": token}
@app.get("/profile-info")
async def get_profile_info(request):
user = request.state.user
return {"username": user.username}
@app.post("/logout")
async def logout(request):
user = request.state.user
await auth_backend.invalidate_token(user.token)
return {"message": "Logged out"}
🧰 Redis Extension
For production environments that require robust session management, enable Redis-backed storage:
from fastapi_auth_jwt import RedisConfig, JWTAuthBackend
redis_config = RedisConfig(
host="localhost",
port=6379,
db=0
)
auth_backend_redis = JWTAuthBackend(
authentication_config=AuthenticationSettings(),
user_schema=User,
storage_config=redis_config,
)
app.add_middleware(
JWTAuthenticationMiddleware,
backend=auth_backend_redis,
exclude_urls=["/sign-up", "/login"]
)
⚙️ Key Components & Configurations
AuthenticationSettings:
secret: JWT signing secret.jwt_algorithm: Algorithm for token signing (default:"HS256").expiration_seconds: Token validity period in seconds.
StorageConfig:
storage_type: Set toMEMORYorREDISfor distributed environments.
RedisConfig:
host,port,db: Core Redis connection parameters.password: Optional if your Redis server requires it.
With these configurations, you can tailor your authentication layer to match your exact operational needs—be it local development, CI/CD pipelines, or full-scale production deployments.
📂 Example Projects
Check out the examples directory for ready-to-run scenarios, including both standard and Redis-backed workflows. Each example demonstrates best practices for integrating JWT authentication into real-world FastAPI applications.
📚 Documentation
Extensive and continuously updated documentation is available at the official docs. There you will find detailed setup guides, API references, configuration tips, and troubleshooting advice.
🛡️ License
This project is licensed under the MIT License. See the LICENSE file for more details.
⭐ Get Involved
Your feedback and contributions are welcome! Here’s how you can support and shape the future of FastAPI Auth JWT:
- ⭐ Star this repository to stay informed and show appreciation.
- 🖇️ Fork the project and experiment with new ideas.
- 🐛 Report Issues or request enhancements via GitHub Issues.
- 🤝 Contribute code, documentation, or examples to help others learn and succeed.
- 📬 Reach Out with questions, suggestions, or integration stories.
With FastAPI Auth JWT, you can implement secure, stable, and scalable JWT authentication in minutes—focusing on building great features instead of reinventing authentication logic.
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 fastapi_auth_jwt-0.1.9.tar.gz.
File metadata
- Download URL: fastapi_auth_jwt-0.1.9.tar.gz
- Upload date:
- Size: 892.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-httpx/0.27.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
947c35d864aa280856d8ce3d32f64e8048d8c362cbcfe0ccfdb4ee9ede72ae24
|
|
| MD5 |
0386f99d2c24be9ad386c610d7aed159
|
|
| BLAKE2b-256 |
e6601562470a8a6464760afc5ce38ce80508742a863b9a11ec42a7ddc1b1b131
|
File details
Details for the file fastapi_auth_jwt-0.1.9-py3-none-any.whl.
File metadata
- Download URL: fastapi_auth_jwt-0.1.9-py3-none-any.whl
- Upload date:
- Size: 22.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-httpx/0.27.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
553fe64a4ec729eac0e98bf6eac6ddea2099efbdc8724d68e5dd51d3e138809d
|
|
| MD5 |
df264641ea15b7afff05d8885a97dd91
|
|
| BLAKE2b-256 |
49a325c395332b8380b142968a11cd5abea324843c14d437c76823aec270839c
|