fastapi-auth-jwt


Namefastapi-auth-jwt JSON
Version 0.1.6 PyPI version JSON
download
home_pageNone
SummaryFastAPI-Auth-JWT is a ready-to-use and easy-to-customize authentication middleware for FastAPI.
upload_time2024-08-14 17:12:07
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords fastapi fastapi-auth-jwt fastapi-auth-middleware fastapi-jwt fastapi-jwt-auth fastapi-middleware fastapi-user-auth fastapi-users redis
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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">
</p>

<p align="center">
    <em>Highly-customizable and ready-to-use session authentication for 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="Pytest">
    </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="Package 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>
</p>


## **✨ Features**

- 🚀 **Effortless Integration**: Seamlessly add JWT authentication to your FastAPI application with just a few lines of code.
- 🛠️ **Highly Customizable**: Tailor the authentication process to fit your specific needs, including custom user models and storage options.
- 🔄 **Sync and Async Support**: Works out of the box with both synchronous and asynchronous FastAPI applications.
- 💾 **Flexible Token Storage**: Supports in-memory token storage for simple applications and Redis for real-world, distributed backends.

## **📦 Installation**

To install the basic package:

```bash
pip install fastapi-auth-jwt
```

If you want to use Redis for token storage, install the package with Redis support:

```bash
pip install fastapi-auth-jwt[redis]
```

## **🚀 Quick Start**

### **🛠️ Basic Setup**

1. **🧑‍💻 Define Your User Schema**: Create a Pydantic model representing the user.

```python
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str
    password: str
    token: Optional[str] = Field(None)
```

2. **⚙️ Configure Authentication Settings**: Set up your authentication configuration.

```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**: Create an instance of the `JWTAuthBackend`.

```python
from fastapi_auth_jwt import JWTAuthBackend

auth_backend = JWTAuthBackend(
    authentication_config=AuthenticationSettings(),
    user_schema=User
)
```

4. **🔌 Add Middleware to Your FastAPI 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"],
)
```

5. **📚 Create Routes**:

```python
@app.post("/sign-up")
async def sign_up(request_data: RegisterSchema):
    return {"message": "User created"}

@app.post("/login")
async def login(request_data: LoginSchema):
    user = User(username=request_data.username, password=request_data.password)
    token = await auth_backend.create_token(user)
    return {"token": token}

@app.get("/profile-info")
async def get_profile_info(request: Request):
    user: User = request.state.user
    return {"username": user.username}

@app.post("/logout")
async def logout(request: Request):
    user: User = request.state.user
    await auth_backend.invalidate_token(user.token)
    return {"message": "Logged out"}
```

### **🧰 Using Redis for Token Storage**

To enable Redis as the storage backend:

```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"],
)
```

## **⚙️ Configuration Options**

### `AuthConfig`

- 🛡️ `secret` (str): Secret key for signing JWT tokens.
- 🧮 `jwt_algorithm` (str): Algorithm used for token encoding (default: `HS256`).
- ⏲️ `expiration_seconds` (int): Token expiration time in seconds (default: `3600`).

### `StorageConfig`

- 🗄️ `storage_type` (StorageTypes): Type of storage backend (`MEMORY` or `REDIS`).

### `RedisConfig`

- 🌐 `host` (str): Redis server hostname (default: `localhost`).
- 🛠️ `port` (int): Redis server port (default: `6379`).
- 🗃️ `db` (int): Redis database index (default: `0`).
- 🔑 `password` (Optional[str]): Redis server password (default: `None`).

## **📂 Example Project**

For a fully working example, refer to the [example directory](https://github.com/deepmancer/fastapi-auth-jwt/example) in the repository.

## **📚 Documentation**

Comprehensive documentation is available in the [docs directory](https://github.com/deepmancer/fastapi-auth-jwt/docs)

## **🤝 Contributing**

We welcome contributions! Please see our [contributing guidelines](CONTRIBUTING.md) for more details.

## **📝 License**

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

## **📬 Contact**

For any questions, suggestions, or issues, please feel free to open an issue or reach out via [GitHub Issues](https://github.com/deepmancer/fastapi-auth-jwt/issues).

---

With `fastapi-auth-jwt`, adding secure, flexible JWT-based authentication to your FastAPI applications is easier than ever. Get started today and enjoy a streamlined authentication experience! 

            

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/8a/ee/29800dae465d6db639dd25a8d8de40f6f86f7b53ad1445aa17526c7e9329/fastapi_auth_jwt-0.1.6.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\">\n</p>\n\n<p align=\"center\">\n    <em>Highly-customizable and ready-to-use session authentication for 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=\"Pytest\">\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=\"Package 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</p>\n\n\n## **\u2728 Features**\n\n- \ud83d\ude80 **Effortless Integration**: Seamlessly add JWT authentication to your FastAPI application with just a few lines of code.\n- \ud83d\udee0\ufe0f **Highly Customizable**: Tailor the authentication process to fit your specific needs, including custom user models and storage options.\n- \ud83d\udd04 **Sync and Async Support**: Works out of the box with both synchronous and asynchronous FastAPI applications.\n- \ud83d\udcbe **Flexible Token Storage**: Supports in-memory token storage for simple applications and Redis for real-world, distributed backends.\n\n## **\ud83d\udce6 Installation**\n\nTo install the basic package:\n\n```bash\npip install fastapi-auth-jwt\n```\n\nIf you want to use Redis for token storage, install the package with Redis support:\n\n```bash\npip install fastapi-auth-jwt[redis]\n```\n\n## **\ud83d\ude80 Quick Start**\n\n### **\ud83d\udee0\ufe0f Basic Setup**\n\n1. **\ud83e\uddd1\u200d\ud83d\udcbb Define Your User Schema**: Create a Pydantic model representing the user.\n\n```python\nfrom pydantic import BaseModel, Field\n\nclass User(BaseModel):\n    username: str\n    password: str\n    token: Optional[str] = Field(None)\n```\n\n2. **\u2699\ufe0f Configure Authentication Settings**: Set up your authentication configuration.\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\n3. **\ud83d\udd27 Initialize the Authentication Backend**: Create an instance of the `JWTAuthBackend`.\n\n```python\nfrom fastapi_auth_jwt import JWTAuthBackend\n\nauth_backend = JWTAuthBackend(\n    authentication_config=AuthenticationSettings(),\n    user_schema=User\n)\n```\n\n4. **\ud83d\udd0c Add Middleware to Your FastAPI 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\"],\n)\n```\n\n5. **\ud83d\udcda Create Routes**:\n\n```python\n@app.post(\"/sign-up\")\nasync def sign_up(request_data: RegisterSchema):\n    return {\"message\": \"User created\"}\n\n@app.post(\"/login\")\nasync def login(request_data: LoginSchema):\n    user = User(username=request_data.username, password=request_data.password)\n    token = await auth_backend.create_token(user)\n    return {\"token\": token}\n\n@app.get(\"/profile-info\")\nasync def get_profile_info(request: Request):\n    user: User = request.state.user\n    return {\"username\": user.username}\n\n@app.post(\"/logout\")\nasync def logout(request: Request):\n    user: User = request.state.user\n    await auth_backend.invalidate_token(user.token)\n    return {\"message\": \"Logged out\"}\n```\n\n### **\ud83e\uddf0 Using Redis for Token Storage**\n\nTo enable Redis as the storage backend:\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## **\u2699\ufe0f Configuration Options**\n\n### `AuthConfig`\n\n- \ud83d\udee1\ufe0f `secret` (str): Secret key for signing JWT tokens.\n- \ud83e\uddee `jwt_algorithm` (str): Algorithm used for token encoding (default: `HS256`).\n- \u23f2\ufe0f `expiration_seconds` (int): Token expiration time in seconds (default: `3600`).\n\n### `StorageConfig`\n\n- \ud83d\uddc4\ufe0f `storage_type` (StorageTypes): Type of storage backend (`MEMORY` or `REDIS`).\n\n### `RedisConfig`\n\n- \ud83c\udf10 `host` (str): Redis server hostname (default: `localhost`).\n- \ud83d\udee0\ufe0f `port` (int): Redis server port (default: `6379`).\n- \ud83d\uddc3\ufe0f `db` (int): Redis database index (default: `0`).\n- \ud83d\udd11 `password` (Optional[str]): Redis server password (default: `None`).\n\n## **\ud83d\udcc2 Example Project**\n\nFor a fully working example, refer to the [example directory](https://github.com/deepmancer/fastapi-auth-jwt/example) in the repository.\n\n## **\ud83d\udcda Documentation**\n\nComprehensive documentation is available in the [docs directory](https://github.com/deepmancer/fastapi-auth-jwt/docs)\n\n## **\ud83e\udd1d Contributing**\n\nWe welcome contributions! Please see our [contributing guidelines](CONTRIBUTING.md) for more details.\n\n## **\ud83d\udcdd License**\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n\n## **\ud83d\udcec Contact**\n\nFor any questions, suggestions, or issues, please feel free to open an issue or reach out via [GitHub Issues](https://github.com/deepmancer/fastapi-auth-jwt/issues).\n\n---\n\nWith `fastapi-auth-jwt`, adding secure, flexible JWT-based authentication to your FastAPI applications is easier than ever. Get started today and enjoy a streamlined authentication experience! \n",
    "bugtrack_url": null,
    "license": null,
    "summary": "FastAPI-Auth-JWT is a ready-to-use and easy-to-customize authentication middleware for FastAPI.",
    "version": "0.1.6",
    "project_urls": {
        "Documentation": "https://github.com/deepmancer/fastapi-auth-jwt#readme",
        "Issues": "https://github.com/deepmancer/fastapi-auth-jwt/issues",
        "Source": "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": "4d9d16c70f85f7176d2b767cca3ebe3aabd03fd5147272cfe3b44430a2a750a4",
                "md5": "d038c197ca9165b53531ce47a806c973",
                "sha256": "43ca4e4985fd51abcbf5af77ddf9aee5cedb883e4c1de5635bda0a65028a34f4"
            },
            "downloads": -1,
            "filename": "fastapi_auth_jwt-0.1.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d038c197ca9165b53531ce47a806c973",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 21176,
            "upload_time": "2024-08-14T17:12:09",
            "upload_time_iso_8601": "2024-08-14T17:12:09.143597Z",
            "url": "https://files.pythonhosted.org/packages/4d/9d/16c70f85f7176d2b767cca3ebe3aabd03fd5147272cfe3b44430a2a750a4/fastapi_auth_jwt-0.1.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8aee29800dae465d6db639dd25a8d8de40f6f86f7b53ad1445aa17526c7e9329",
                "md5": "0615de377471940c0897e635efba07b8",
                "sha256": "209798ed6b47456e212b3cb99ee98a03de6516b124e2f93cae9ffc422ac32844"
            },
            "downloads": -1,
            "filename": "fastapi_auth_jwt-0.1.6.tar.gz",
            "has_sig": false,
            "md5_digest": "0615de377471940c0897e635efba07b8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 889591,
            "upload_time": "2024-08-14T17:12:07",
            "upload_time_iso_8601": "2024-08-14T17:12:07.600493Z",
            "url": "https://files.pythonhosted.org/packages/8a/ee/29800dae465d6db639dd25a8d8de40f6f86f7b53ad1445aa17526c7e9329/fastapi_auth_jwt-0.1.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-08-14 17:12:07",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "deepmancer",
    "github_project": "fastapi-auth-jwt#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-auth-jwt"
}
        
Elapsed time: 1.09500s