From dad927ba342fc737907ea2551db1c044174b7f68 Mon Sep 17 00:00:00 2001 From: deepmancer Date: Tue, 10 Dec 2024 17:15:35 +0330 Subject: [PATCH] Update README.md to enhance clarity and structure, including improved descriptions, added table of contents, and refined installation instructions. --- README.md | 180 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 123 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 326dd3a..58f8460 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,19 @@ # FastAPI Auth JWT

- FastAPI Auth JWT +FastAPI Auth JWT

- Highly-customizable and ready-to-use session authentication for FastAPI applications + Seamless, production-ready JWT authentication for your FastAPI applications.

+

- + Build Status - Package version + PyPI Version Coverage @@ -24,41 +25,86 @@ --- -| **Source Code** | **Website** | -|:-----------------|:------------| -| github.com/deepmancer/fastapi-auth-jwt | deepmancer.github.io/fastapi-auth-jwt | +| **Source Code** | **Documentation** | **Live Demos** | +|:----------------|:------------------|:---------------| +| [GitHub](https://github.com/deepmancer/fastapi-auth-jwt) | [Docs](https://deepmancer.github.io/fastapi-auth-jwt/) | [Examples](https://github.com/deepmancer/fastapi-auth-jwt/tree/main/examples) | --- -## **โœจ Features** +## Table of Contents +- [FastAPI Auth JWT](#fastapi-auth-jwt) + - [Table of Contents](#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. -- ๐Ÿš€ **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. +- ๐Ÿš€ **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** +--- -To install the basic package: +## ๐Ÿ“ฆ Installation +**Basic Installation**: ```bash pip install fastapi-auth-jwt ``` -If you want to use Redis for token storage, install the package with Redis support: - +**With Redis Support**: ```bash pip install fastapi-auth-jwt[redis] ``` -## **๐Ÿš€ Quick Start** +**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 -### **๐Ÿ› ๏ธ Basic Setup** +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 Your User Schema**: Create a Pydantic model representing the user. +### ๐Ÿ› ๏ธ 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 @@ -66,7 +112,8 @@ class User(BaseModel): token: Optional[str] = Field(None) ``` -2. **โš™๏ธ Configure Authentication Settings**: Set up your authentication configuration. +### โš™๏ธ 2. Configure Authentication Settings +Specify your JWT signing secrets, algorithms, and token expiration times. ```python from pydantic import BaseModel @@ -77,7 +124,8 @@ class AuthenticationSettings(BaseModel): expiration_seconds: int = 3600 # 1 hour ``` -3. **๐Ÿ”ง Initialize the Authentication Backend**: Create an instance of the `JWTAuthBackend`. +### ๐Ÿ”ง 3. Initialize the Authentication Backend +Integrate the `JWTAuthBackend` using your settings and user schema. ```python from fastapi_auth_jwt import JWTAuthBackend @@ -88,7 +136,8 @@ auth_backend = JWTAuthBackend( ) ``` -4. **๐Ÿ”Œ Add Middleware to Your FastAPI Application**: +### ๐Ÿ”Œ 4. Add Middleware to FastAPI +Hook the authentication middleware into your application. ```python from fastapi import FastAPI @@ -99,40 +148,44 @@ app = FastAPI() app.add_middleware( JWTAuthenticationMiddleware, backend=auth_backend, - exclude_urls=["/sign-up", "/login"], + exclude_urls=["/sign-up", "/login"], # Public endpoints ) ``` -5. **๐Ÿ“š Create Routes**: +### ๐Ÿ“š 5. Define Your Routes +Secure routes automatically validate tokens before accessing the request state. ```python @app.post("/sign-up") -async def sign_up(request_data: RegisterSchema): +async def sign_up(user: User): + # Implement user creation logic here return {"message": "User created"} @app.post("/login") -async def login(request_data: LoginSchema): +async def login(user: User): token = await auth_backend.create_token( - username=request_data.username, - password=request_data.password, + {"username": user.username, "password": user.password}, + expiration=3600 ) return {"token": token} @app.get("/profile-info") -async def get_profile_info(request: Request): - user: User = request.state.user +async def get_profile_info(request): + user = request.state.user return {"username": user.username} @app.post("/logout") -async def logout(request: Request): - user: User = request.state.user +async def logout(request): + user = request.state.user await auth_backend.invalidate_token(user.token) return {"message": "Logged out"} ``` -### **๐Ÿงฐ Redis Extension** +--- + +## ๐Ÿงฐ Redis Extension -To enable Redis as the storage backend: +For production environments that require robust session management, enable Redis-backed storage: ```python from fastapi_auth_jwt import RedisConfig, JWTAuthBackend @@ -140,7 +193,7 @@ from fastapi_auth_jwt import RedisConfig, JWTAuthBackend redis_config = RedisConfig( host="localhost", port=6379, - db=0, + db=0 ) auth_backend_redis = JWTAuthBackend( @@ -152,45 +205,58 @@ auth_backend_redis = JWTAuthBackend( app.add_middleware( JWTAuthenticationMiddleware, backend=auth_backend_redis, - exclude_urls=["/sign-up", "/login"], + exclude_urls=["/sign-up", "/login"] ) ``` -## **โš™๏ธ Configuration Options** +--- -### `AuthConfig` +## โš™๏ธ Key Components & Configurations -- ๐Ÿ›ก๏ธ `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`). +**AuthenticationSettings**: +- `secret`: JWT signing secret. +- `jwt_algorithm`: Algorithm for token signing (default: `"HS256"`). +- `expiration_seconds`: Token validity period in seconds. -### `StorageConfig` +**StorageConfig**: +- `storage_type`: Set to `MEMORY` or `REDIS` for distributed environments. -- ๐Ÿ—„๏ธ `storage_type` (StorageTypes): Type of storage backend (`MEMORY` or `REDIS`). +**RedisConfig**: +- `host`, `port`, `db`: Core Redis connection parameters. +- `password`: Optional if your Redis server requires it. -### `RedisConfig` +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. -- ๐ŸŒ `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 Projects** +## ๐Ÿ“‚ Example Projects -For fully working examples, refer to the [examples directory](https://github.com/deepmancer/fastapi-auth-jwt/tree/main/examples) in the repository. +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** +--- -Complete documentation is available in the [docs directory](https://github.com/deepmancer/fastapi-auth-jwt/blob/main/docs/README.md). +## ๐Ÿ“š Documentation -## **๐Ÿ“ License** +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. -This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. +--- -## **๐Ÿ“ฌ Contact** +## ๐Ÿ›ก๏ธ License -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). +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. --- -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! +## โญ 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.