# FastAPI Auth JWT
<p align="center">
<img src="https://raw.githubusercontent.com/deepmancer/fastapi-auth-jwt/main/fastapi_auth_jwt_logo.png" alt="FastAPI Auth JWT" style="width: 80%;">
</p>
<p align="center">
<em>Seamless, production-ready JWT authentication for your FastAPI applications.</em>
</p>
<p align="center">
<a href="https://github.com/deepmancer/fastapi-auth-jwt/actions" target="_blank">
<img src="https://github.com/deepmancer/fastapi-auth-jwt/workflows/Build/badge.svg" alt="Build Status">
</a>
<a href="https://pypi.org/project/fastapi-auth-jwt/" target="_blank">
<img src="https://img.shields.io/pypi/v/fastapi-auth-jwt.svg" alt="PyPI Version">
</a>
<a href="https://codecov.io/gh/deepmancer/fastapi-auth-jwt" target="_blank">
<img src="https://codecov.io/gh/deepmancer/fastapi-auth-jwt/branch/main/graph/badge.svg" alt="Coverage">
</a>
<a href="https://github.com/deepmancer/fastapi-auth-jwt/blob/main/LICENSE" target="_blank">
<img src="https://img.shields.io/github/license/deepmancer/fastapi-auth-jwt.svg" alt="License">
</a>
</p>
---
| **Source Code** | **Documentation** | **PyPI** | **Live Demos** |
|:----------------|:------------------|:---------|:---------------|
| <a href="https://github.com/deepmancer/fastapi-auth-jwt" target="_blank">GitHub</a> | <a href="https://deepmancer.github.io/fastapi-auth-jwt/" target="_blank">Docs</a> | <a href="https://pypi.org/project/fastapi-auth-jwt/" target="_blank">PyPI</a> | <a href="https://github.com/deepmancer/fastapi-auth-jwt/tree/main/examples" target="_blank">Examples</a> |
---
## 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 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.
```python
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.
```python
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.
```python
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.
```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, 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 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.
Raw data
{
"_id": null,
"home_page": null,
"name": "fastapi-auth-jwt",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "fastapi, fastapi-auth-jwt, fastapi-auth-middleware, fastapi-jwt, fastapi-jwt-auth, fastapi-middleware, fastapi-user-auth, fastapi-users, redis",
"author": null,
"author_email": "deepmancer <alirezaheidari.cs@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/4e/69/bf6a732aadfbd0fc2586c6260e103554a062e21540b759f2c6063b1cf54b/fastapi_auth_jwt-0.1.11.tar.gz",
"platform": null,
"description": "# FastAPI Auth JWT\n\n<p align=\"center\">\n<img src=\"https://raw.githubusercontent.com/deepmancer/fastapi-auth-jwt/main/fastapi_auth_jwt_logo.png\" alt=\"FastAPI Auth JWT\" style=\"width: 80%;\">\n</p>\n\n<p align=\"center\">\n <em>Seamless, production-ready JWT authentication for your FastAPI applications.</em>\n</p>\n\n<p align=\"center\">\n <a href=\"https://github.com/deepmancer/fastapi-auth-jwt/actions\" target=\"_blank\">\n <img src=\"https://github.com/deepmancer/fastapi-auth-jwt/workflows/Build/badge.svg\" alt=\"Build Status\">\n </a>\n <a href=\"https://pypi.org/project/fastapi-auth-jwt/\" target=\"_blank\">\n <img src=\"https://img.shields.io/pypi/v/fastapi-auth-jwt.svg\" alt=\"PyPI Version\">\n </a>\n <a href=\"https://codecov.io/gh/deepmancer/fastapi-auth-jwt\" target=\"_blank\">\n <img src=\"https://codecov.io/gh/deepmancer/fastapi-auth-jwt/branch/main/graph/badge.svg\" alt=\"Coverage\">\n </a>\n <a href=\"https://github.com/deepmancer/fastapi-auth-jwt/blob/main/LICENSE\" target=\"_blank\">\n <img src=\"https://img.shields.io/github/license/deepmancer/fastapi-auth-jwt.svg\" alt=\"License\">\n </a>\n</p>\n\n---\n\n| **Source Code** | **Documentation** | **PyPI** | **Live Demos** |\n|:----------------|:------------------|:---------|:---------------|\n| <a href=\"https://github.com/deepmancer/fastapi-auth-jwt\" target=\"_blank\">GitHub</a> | <a href=\"https://deepmancer.github.io/fastapi-auth-jwt/\" target=\"_blank\">Docs</a> | <a href=\"https://pypi.org/project/fastapi-auth-jwt/\" target=\"_blank\">PyPI</a> | <a href=\"https://github.com/deepmancer/fastapi-auth-jwt/tree/main/examples\" target=\"_blank\">Examples</a> |\n\n---\n\n## Table of Contents\n- [\ud83c\udf1f Why FastAPI Auth JWT?](#-why-fastapi-auth-jwt)\n- [\ud83d\udce6 Installation](#-installation)\n- [\ud83d\ude80 Getting Started](#-getting-started)\n - [\ud83d\udee0\ufe0f 1. Define a User Model](#\ufe0f-1-define-a-user-model)\n - [\u2699\ufe0f 2. Configure Authentication Settings](#\ufe0f-2-configure-authentication-settings)\n - [\ud83d\udd27 3. Initialize the Authentication Backend](#-3-initialize-the-authentication-backend)\n - [\ud83d\udd0c 4. Add Middleware to FastAPI](#-4-add-middleware-to-fastapi)\n - [\ud83d\udcda 5. Define Your Routes](#-5-define-your-routes)\n- [\ud83e\uddf0 Redis Extension](#-redis-extension)\n- [\u2699\ufe0f Key Components \\& Configurations](#\ufe0f-key-components--configurations)\n- [\ud83d\udcc2 Example Projects](#-example-projects)\n- [\ud83d\udcda Documentation](#-documentation)\n- [\ud83d\udee1\ufe0f License](#\ufe0f-license)\n- [\u2b50 Get Involved](#-get-involved)\n\n---\n\n## \ud83c\udf1f Why FastAPI Auth JWT?\n\n**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. \n\n- \ud83d\ude80 **Quick Setup**: Integrate JWT authentication into new or existing FastAPI projects in just a few lines.\n- \ud83d\udee0\ufe0f **Configurable & Extensible**: Easily adapt authentication rules, user schemas, and token lifetimes to meet dynamic requirements.\n- \ud83d\udd04 **Sync & Async Compatible**: Whether your routes are synchronous or asynchronous, the middleware and backend integrate smoothly.\n- \ud83d\udcbe **Multiple Storage Backends**: Start with in-memory caching for simplicity, then scale transparently to Redis for high-availability, distributed architectures.\n- \u2705 **Thoroughly Tested & Documented**: A well-structured codebase with comprehensive tests and clear documentation means you can rely on stable, predictable behavior.\n\n---\n\n## \ud83d\udce6 Installation\n\n**Basic Installation**:\n```bash\npip install fastapi-auth-jwt\n```\n\n**With Redis Support**:\n```bash\npip install fastapi-auth-jwt[redis]\n```\n\n**From Source**:\n1. Clone the repository:\n ```bash\n git clone https://github.com/deepmancer/fastapi-auth-jwt.git\n ```\n2. Navigate to the directory:\n ```bash\n cd fastapi-auth-jwt\n ```\n3. Install the package:\n ```bash\n pip install .\n ```\n\n**Requirements**: \n- Python 3.8+ \n- FastAPI 0.65.2+ \n\n---\n\n## \ud83d\ude80 Getting Started\n\nBelow 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).\n\n### \ud83d\udee0\ufe0f 1. Define a User Model\nCreate a simple Pydantic model representing your user entity.\n\n```python\nfrom pydantic import BaseModel, Field\nfrom typing import Optional\n\nclass User(BaseModel):\n username: str\n password: str\n token: Optional[str] = Field(None)\n```\n\n### \u2699\ufe0f 2. Configure Authentication Settings\nSpecify your JWT signing secrets, algorithms, and token expiration times.\n\n```python\nfrom pydantic import BaseModel\n\nclass AuthenticationSettings(BaseModel):\n secret: str = \"your-secret-key\"\n jwt_algorithm: str = \"HS256\"\n expiration_seconds: int = 3600 # 1 hour\n```\n\n### \ud83d\udd27 3. Initialize the Authentication Backend\nIntegrate the `JWTAuthBackend` using your settings and user schema.\n\n```python\nfrom fastapi_auth_jwt import JWTAuthBackend\n\nauth_backend = JWTAuthBackend(\n authentication_config=AuthenticationSettings(),\n user_schema=User\n)\n```\n\n### \ud83d\udd0c 4. Add Middleware to FastAPI\nHook the authentication middleware into your application.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_auth_jwt import JWTAuthenticationMiddleware\n\napp = FastAPI()\n\napp.add_middleware(\n JWTAuthenticationMiddleware,\n backend=auth_backend,\n exclude_urls=[\"/sign-up\", \"/login\"], # Public endpoints\n)\n```\n\n### \ud83d\udcda 5. Define Your Routes\nSecure routes automatically validate tokens before accessing the request state.\n\n```python\n@app.post(\"/sign-up\")\nasync def sign_up(user: User):\n # Implement user creation logic here\n return {\"message\": \"User created\"}\n\n@app.post(\"/login\")\nasync def login(user: User):\n token = await auth_backend.create_token(\n {\"username\": user.username, \"password\": user.password},\n expiration=3600\n )\n return {\"token\": token}\n\n@app.get(\"/profile-info\")\nasync def get_profile_info(request):\n user = request.state.user\n return {\"username\": user.username}\n\n@app.post(\"/logout\")\nasync def logout(request):\n user = request.state.user\n await auth_backend.invalidate_token(user.token)\n return {\"message\": \"Logged out\"}\n```\n\n---\n\n## \ud83e\uddf0 Redis Extension\n\nFor production environments that require robust session management, enable Redis-backed storage:\n\n```python\nfrom fastapi_auth_jwt import RedisConfig, JWTAuthBackend\n\nredis_config = RedisConfig(\n host=\"localhost\",\n port=6379,\n db=0\n)\n\nauth_backend_redis = JWTAuthBackend(\n authentication_config=AuthenticationSettings(),\n user_schema=User,\n storage_config=redis_config,\n)\n\napp.add_middleware(\n JWTAuthenticationMiddleware,\n backend=auth_backend_redis,\n exclude_urls=[\"/sign-up\", \"/login\"]\n)\n```\n\n---\n\n## \u2699\ufe0f Key Components & Configurations\n\n**AuthenticationSettings**: \n- `secret`: JWT signing secret. \n- `jwt_algorithm`: Algorithm for token signing (default: `\"HS256\"`). \n- `expiration_seconds`: Token validity period in seconds.\n\n**StorageConfig**: \n- `storage_type`: Set to `MEMORY` or `REDIS` for distributed environments.\n\n**RedisConfig**: \n- `host`, `port`, `db`: Core Redis connection parameters. \n- `password`: Optional if your Redis server requires it.\n\nWith these configurations, you can tailor your authentication layer to match your exact operational needs\u2014be it local development, CI/CD pipelines, or full-scale production deployments.\n\n---\n\n## \ud83d\udcc2 Example Projects\n\nCheck 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.\n\n---\n\n## \ud83d\udcda Documentation\n\nExtensive 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.\n\n---\n\n## \ud83d\udee1\ufe0f License\n\nThis project is licensed under the MIT License. See the [LICENSE](https://github.com/deepmancer/fastapi-auth-jwt/blob/main/LICENSE) file for more details.\n\n---\n\n## \u2b50 Get Involved\n\nYour feedback and contributions are welcome! Here\u2019s how you can support and shape the future of **FastAPI Auth JWT**:\n\n- \u2b50 **Star** this repository to stay informed and show appreciation.\n- \ud83d\udd87\ufe0f **Fork** the project and experiment with new ideas.\n- \ud83d\udc1b **Report Issues** or request enhancements via [GitHub Issues](https://github.com/deepmancer/fastapi-auth-jwt/issues).\n- \ud83e\udd1d **Contribute** code, documentation, or examples to help others learn and succeed.\n- \ud83d\udcec **Reach Out** with questions, suggestions, or integration stories.\n\n--- \n\nWith **FastAPI Auth JWT**, you can implement secure, stable, and scalable JWT authentication in minutes\u2014focusing on building great features instead of reinventing authentication logic.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "FastAPI-Auth-JWT is a ready-to-use and easy-to-customize authentication middleware for FastAPI.",
"version": "0.1.11",
"project_urls": {
"Changelog": "https://github.com/deepmancer/fastapi-auth-jwt/blob/main/CHANGELOG.md",
"Documentation": "https://deepmancer.github.io/fastapi-auth-jwt",
"Homepage": "https://deepmancer.github.io/fastapi-auth-jwt",
"Issues": "https://github.com/deepmancer/fastapi-auth-jwt/issues",
"Repository": "https://github.com/deepmancer/fastapi-auth-jwt"
},
"split_keywords": [
"fastapi",
" fastapi-auth-jwt",
" fastapi-auth-middleware",
" fastapi-jwt",
" fastapi-jwt-auth",
" fastapi-middleware",
" fastapi-user-auth",
" fastapi-users",
" redis"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "7ac27628d6261499384a447adaff701b1f7bdaac7f53ff6389203128aa2cbfd4",
"md5": "5d99240709da73c537b1a28e18c2ebd4",
"sha256": "c7c66896d86deca32ed1508b007e9a01eb955e326a4e9e8dbee6381fbda78f74"
},
"downloads": -1,
"filename": "fastapi_auth_jwt-0.1.11-py3-none-any.whl",
"has_sig": false,
"md5_digest": "5d99240709da73c537b1a28e18c2ebd4",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 22580,
"upload_time": "2024-12-10T14:22:54",
"upload_time_iso_8601": "2024-12-10T14:22:54.610379Z",
"url": "https://files.pythonhosted.org/packages/7a/c2/7628d6261499384a447adaff701b1f7bdaac7f53ff6389203128aa2cbfd4/fastapi_auth_jwt-0.1.11-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "4e69bf6a732aadfbd0fc2586c6260e103554a062e21540b759f2c6063b1cf54b",
"md5": "bf387efd88059c6ee9a1ab76062ca110",
"sha256": "19e434eceab1ab4207f28603d1d8457e35a2701591e2d57c5194ef62762a11e0"
},
"downloads": -1,
"filename": "fastapi_auth_jwt-0.1.11.tar.gz",
"has_sig": false,
"md5_digest": "bf387efd88059c6ee9a1ab76062ca110",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 892758,
"upload_time": "2024-12-10T14:23:00",
"upload_time_iso_8601": "2024-12-10T14:23:00.422801Z",
"url": "https://files.pythonhosted.org/packages/4e/69/bf6a732aadfbd0fc2586c6260e103554a062e21540b759f2c6063b1cf54b/fastapi_auth_jwt-0.1.11.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-10 14:23:00",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "deepmancer",
"github_project": "fastapi-auth-jwt",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "fastapi-auth-jwt"
}