{"id":15020954,"url":"https://github.com/deepmancer/fastapi-auth-jwt","last_synced_at":"2025-10-18T15:27:54.087Z","repository":{"id":252917188,"uuid":"839284850","full_name":"deepmancer/fastapi-auth-jwt","owner":"deepmancer","description":"Simple to use FastAPI JWT authentication middleware","archived":false,"fork":false,"pushed_at":"2024-12-10T14:22:24.000Z","size":1450,"stargazers_count":5,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-01T00:26:13.642Z","etag":null,"topics":["authentication","authorization","bearer-authentication","fastapi","fastapi-extension","fastapi-middleware","jwt","jwt-authentication","python3","starlette","starlette-middleware","token-based-authentication"],"latest_commit_sha":null,"homepage":"https://deepmancer.github.io/fastapi-auth-jwt/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/deepmancer.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-07T09:53:33.000Z","updated_at":"2024-12-10T14:22:28.000Z","dependencies_parsed_at":"2024-08-16T12:54:18.981Z","dependency_job_id":"30aea6b0-f533-43d6-aad0-c33ef550b6bd","html_url":"https://github.com/deepmancer/fastapi-auth-jwt","commit_stats":null,"previous_names":["deepmancer/fastapi-auth-jwt"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepmancer%2Ffastapi-auth-jwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepmancer%2Ffastapi-auth-jwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepmancer%2Ffastapi-auth-jwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepmancer%2Ffastapi-auth-jwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/deepmancer","download_url":"https://codeload.github.com/deepmancer/fastapi-auth-jwt/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238397230,"owners_count":19465137,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","authorization","bearer-authentication","fastapi","fastapi-extension","fastapi-middleware","jwt","jwt-authentication","python3","starlette","starlette-middleware","token-based-authentication"],"created_at":"2024-09-24T19:55:56.158Z","updated_at":"2025-10-18T15:27:49.048Z","avatar_url":"https://github.com/deepmancer.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI Auth JWT\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://raw.githubusercontent.com/deepmancer/fastapi-auth-jwt/main/fastapi_auth_jwt_logo.png\" alt=\"FastAPI Auth JWT\" style=\"width: 80%;\"\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003cem\u003eSeamless, production-ready JWT authentication for your FastAPI applications.\u003c/em\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/deepmancer/fastapi-auth-jwt/actions\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://github.com/deepmancer/fastapi-auth-jwt/workflows/Build/badge.svg\" alt=\"Build Status\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://pypi.org/project/fastapi-auth-jwt/\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://img.shields.io/pypi/v/fastapi-auth-jwt.svg\" alt=\"PyPI Version\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://codecov.io/gh/deepmancer/fastapi-auth-jwt\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://codecov.io/gh/deepmancer/fastapi-auth-jwt/branch/main/graph/badge.svg\" alt=\"Coverage\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/deepmancer/fastapi-auth-jwt/blob/main/LICENSE\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://img.shields.io/github/license/deepmancer/fastapi-auth-jwt.svg\" alt=\"License\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n---\n\n| **Source Code** | **Documentation** | **PyPI** | **Live Demos** |\n|:----------------|:------------------|:---------|:---------------|\n| \u003ca href=\"https://github.com/deepmancer/fastapi-auth-jwt\" target=\"_blank\"\u003eGitHub\u003c/a\u003e | \u003ca href=\"https://deepmancer.github.io/fastapi-auth-jwt/\" target=\"_blank\"\u003eDocs\u003c/a\u003e | \u003ca href=\"https://pypi.org/project/fastapi-auth-jwt/\" target=\"_blank\"\u003ePyPI\u003c/a\u003e | \u003ca href=\"https://github.com/deepmancer/fastapi-auth-jwt/tree/main/examples\" target=\"_blank\"\u003eExamples\u003c/a\u003e |\n\n---\n\n## Table of Contents\n- [🌟 Why FastAPI Auth JWT?](#-why-fastapi-auth-jwt)\n- [📦 Installation](#-installation)\n- [🚀 Getting Started](#-getting-started)\n    - [🛠️ 1. Define a User Model](#️-1-define-a-user-model)\n    - [⚙️ 2. Configure Authentication Settings](#️-2-configure-authentication-settings)\n    - [🔧 3. Initialize the Authentication Backend](#-3-initialize-the-authentication-backend)\n    - [🔌 4. Add Middleware to FastAPI](#-4-add-middleware-to-fastapi)\n    - [📚 5. Define Your Routes](#-5-define-your-routes)\n- [🧰 Redis Extension](#-redis-extension)\n- [⚙️ Key Components \\\u0026 Configurations](#️-key-components--configurations)\n- [📂 Example Projects](#-example-projects)\n- [📚 Documentation](#-documentation)\n- [🛡️ License](#️-license)\n- [⭐ Get Involved](#-get-involved)\n\n---\n\n## 🌟 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- 🚀 **Quick Setup**: Integrate JWT authentication into new or existing FastAPI projects in just a few lines.\n- 🛠️ **Configurable \u0026 Extensible**: Easily adapt authentication rules, user schemas, and token lifetimes to meet dynamic requirements.\n- 🔄 **Sync \u0026 Async Compatible**: Whether your routes are synchronous or asynchronous, the middleware and backend integrate smoothly.\n- 💾 **Multiple Storage Backends**: Start with in-memory caching for simplicity, then scale transparently to Redis for high-availability, distributed architectures.\n- ✅ **Thoroughly Tested \u0026 Documented**: A well-structured codebase with comprehensive tests and clear documentation means you can rely on stable, predictable behavior.\n\n---\n\n## 📦 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## 🚀 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### 🛠️ 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### ⚙️ 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### 🔧 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### 🔌 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### 📚 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## 🧰 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## ⚙️ Key Components \u0026 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—be it local development, CI/CD pipelines, or full-scale production deployments.\n\n---\n\n## 📂 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## 📚 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## 🛡️ 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## ⭐ Get Involved\n\nYour feedback and contributions are welcome! Here’s how you can support and shape the future of **FastAPI Auth JWT**:\n\n- ⭐ **Star** this repository to stay informed and show appreciation.\n- 🖇️ **Fork** the project and experiment with new ideas.\n- 🐛 **Report Issues** or request enhancements via [GitHub Issues](https://github.com/deepmancer/fastapi-auth-jwt/issues).\n- 🤝 **Contribute** code, documentation, or examples to help others learn and succeed.\n- 📬 **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—focusing on building great features instead of reinventing authentication logic.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeepmancer%2Ffastapi-auth-jwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeepmancer%2Ffastapi-auth-jwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeepmancer%2Ffastapi-auth-jwt/lists"}