Seamless, production-ready JWT authentication for your FastAPI applications.
Source Code | Documentation | PyPI | Live Demos |
---|---|---|---|
GitHub | Docs | PyPI | Examples |
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.
Basic Installation:
pip install fastapi-auth-jwt
With Redis Support:
pip install fastapi-auth-jwt[redis]
From Source:
git clone https://github.com/deepmancer/fastapi-auth-jwt.git
cd fastapi-auth-jwt
pip install .
Requirements:
Below is a high-level example to get you started. For more advanced use cases and patterns, refer to the examples section and the official docs.
Create a simple Pydantic model representing your user entity.
from pydantic import BaseModel, Field
from typing import Optional
class User(BaseModel):
username: str
password: str
token: Optional[str] = Field(None)
Specify your JWT signing secrets, algorithms, and token expiration times.
from pydantic import BaseModel
class AuthenticationSettings(BaseModel):
secret: str = "your-secret-key"
jwt_algorithm: str = "HS256"
expiration_seconds: int = 3600 # 1 hour
Integrate the JWTAuthBackend
using your settings and user schema.
from fastapi_auth_jwt import JWTAuthBackend
auth_backend = JWTAuthBackend(
authentication_config=AuthenticationSettings(),
user_schema=User
)
Hook the authentication middleware into your application.
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
)
Secure routes automatically validate tokens before accessing the request state.
@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"}
For production environments that require robust session management, enable Redis-backed storage:
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"]
)
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.
Check out the examples directory 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.
Extensive and continuously updated documentation is available at the official docs. 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 file for more details.
Your feedback and contributions are welcome! Hereβs how you can support and shape the future of FastAPI Auth JWT:
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.