https://github.com/deepmancer/fastapi-auth-jwt
Simple to use FastAPI JWT authentication middleware
https://github.com/deepmancer/fastapi-auth-jwt
authentication authorization bearer-authentication fastapi fastapi-extension fastapi-middleware jwt jwt-authentication python3 starlette starlette-middleware token-based-authentication
Last synced: 5 months ago
JSON representation
Simple to use FastAPI JWT authentication middleware
- Host: GitHub
- URL: https://github.com/deepmancer/fastapi-auth-jwt
- Owner: deepmancer
- License: mit
- Created: 2024-08-07T09:53:33.000Z (11 months ago)
- Default Branch: main
- Last Pushed: 2024-12-10T14:22:24.000Z (7 months ago)
- Last Synced: 2025-02-01T00:26:13.642Z (5 months ago)
- Topics: authentication, authorization, bearer-authentication, fastapi, fastapi-extension, fastapi-middleware, jwt, jwt-authentication, python3, starlette, starlette-middleware, token-based-authentication
- Language: Python
- Homepage: https://deepmancer.github.io/fastapi-auth-jwt/
- Size: 1.38 MB
- Stars: 5
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# FastAPI Auth JWT
![]()
Seamless, production-ready JWT authentication for your FastAPI applications.---
| **Source Code** | **Documentation** | **PyPI** | **Live Demos** |
|:----------------|:------------------|:---------|:---------------|
| GitHub | Docs | PyPI | Examples |---
## Table of Contents
- [π Why FastAPI Auth JWT?](#-why-fastapi-auth-jwt)
- [π¦ Installation](#-installation)
- [π Getting Started](#-getting-started)
- [π οΈ 1. Define a User Model](#οΈ-1-define-a-user-model)
- [βοΈ 2. Configure Authentication Settings](#οΈ-2-configure-authentication-settings)
- [π§ 3. Initialize the Authentication Backend](#-3-initialize-the-authentication-backend)
- [π 4. Add Middleware to FastAPI](#-4-add-middleware-to-fastapi)
- [π 5. Define Your Routes](#-5-define-your-routes)
- [π§° Redis Extension](#-redis-extension)
- [βοΈ Key Components \& Configurations](#οΈ-key-components--configurations)
- [π Example Projects](#-example-projects)
- [π Documentation](#-documentation)
- [π‘οΈ License](#οΈ-license)
- [β Get Involved](#-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**:
```bash
pip install fastapi-auth-jwt
```**With Redis Support**:
```bash
pip install fastapi-auth-jwt[redis]
```**From Source**:
1. Clone the repository:
```bash
git clone https://github.com/deepmancer/fastapi-auth-jwt.git
```
2. Navigate to the directory:
```bash
cd fastapi-auth-jwt
```
3. Install the package:
```bash
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](#-example-projects) section and the [official docs](#-documentation).
### π οΈ 1. Define a User Model
Create a simple Pydantic model representing your user entity.```python
from pydantic import BaseModel, Field
from typing import Optionalclass 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.```python
from pydantic import BaseModelclass 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.```python
from fastapi_auth_jwt import JWTAuthBackendauth_backend = JWTAuthBackend(
authentication_config=AuthenticationSettings(),
user_schema=User
)
```### π 4. Add Middleware to FastAPI
Hook the authentication middleware into your application.```python
from fastapi import FastAPI
from fastapi_auth_jwt import JWTAuthenticationMiddlewareapp = 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.```python
@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:
```python
from fastapi_auth_jwt import RedisConfig, JWTAuthBackendredis_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 to `MEMORY` or `REDIS` for 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](https://github.com/deepmancer/fastapi-auth-jwt/tree/main/examples) 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](https://deepmancer.github.io/fastapi-auth-jwt/). 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](https://github.com/deepmancer/fastapi-auth-jwt/blob/main/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](https://github.com/deepmancer/fastapi-auth-jwt/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.