Skip to main content

A FastAPI Middleware for Secure JWT Authentication with Redis Caching

Project description

redis-jwt-auth

A FastAPI Middleware for Secure JWT Authentication with Redis Caching

Overview

redis-jwt-auth is a FastAPI middleware that provides JWT authentication with Redis-based token caching. It enhances performance by reducing database queries and ensures single active sessions per user. The package supports token rotation, secure session management, and seamless integration into FastAPI applications.

Key Features

✅ JWT Token Validation – Decodes and verifies JWT tokens efficiently.

✅ Redis Caching – Stores access tokens, refresh tokens, and user objects in Redis for fast retrieval.

✅ Single Active Session – Ensures a user is logged in from only one device at a time.

✅ Token Rotation (Optional) – Enhances security by refreshing tokens on every request.

✅ Soft-Delete Support – Ensures inactive or deleted users cannot authenticate.

✅ Easy Middleware Integration – Plug and play support for FastAPI applications.

Installation

Install redis-jwt-auth using pip:

pip install redis-jwt-auth

Usage

  1. Initialize Middleware in FastAPI

from fastapi import FastAPI from redis_jwt_auth.middleware import TokenMiddleware

app = FastAPI()

app.add_middleware( TokenMiddleware, redis_host="localhost", redis_port=6379, secret_key="your_jwt_secret", enable_token_rotation=True # Set to False if you don't want token rotation )

  1. Protect Routes

Use the middleware to protect routes automatically. The validated user will be available in request.state.user.

from fastapi import Depends, Request

@app.get("/protected-route") async def protected_route(request: Request): user = request.state.user # Retrieved from Redis cache return {"message": f"Welcome, {user['username']}!"}

  1. Redis Caching Structure

Action

Description

On login

Tokens and user details are stored in Redis.

On request

JWT is validated, checked against Redis, and user details are fetched.

On logout

Tokens are deleted from Redis, ensuring session invalidation.

Configuration Options

Parameter

Type

Default

Description

redis_host

str

"localhost"

Redis server hostname

redis_port

int

6379

Redis server port

secret_key

str

Required

Secret key for JWT validation

enable_token_rotation

bool

False

Enables automatic token refresh

Future Enhancements

🚀 Support multiple active sessions per user

🚀 Role-based access control (RBAC)

🚀 Integration with OAuth & third-party authentication

🚀 Performance monitoring with Redis cache metrics

Contributing

Want to improve redis-jwt-auth? Feel free to submit issues or pull requests in the GitHub repository!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

redis_jwt_auth-0.1.1.tar.gz (4.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

redis_jwt_auth-0.1.1-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

Details for the file redis_jwt_auth-0.1.1.tar.gz.

File metadata

  • Download URL: redis_jwt_auth-0.1.1.tar.gz
  • Upload date:
  • Size: 4.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for redis_jwt_auth-0.1.1.tar.gz
Algorithm Hash digest
SHA256 3942706a5765cd9210e0f5e0fc389a32588de8503e4bd2ce1968e2c3b86da8d8
MD5 66f70219c479c49868e477401615b836
BLAKE2b-256 7671a982b444e9fd2b0d7e9ff425b13ddea0e304b6c787f1abeff1a4dd87712e

See more details on using hashes here.

File details

Details for the file redis_jwt_auth-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: redis_jwt_auth-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 5.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for redis_jwt_auth-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 26619a114fdd52989092124be0624c5d3eadde7f8e43f9f89713b7479363be81
MD5 dabb59130d6cce6afbfc0d234e49e0ba
BLAKE2b-256 b9b536ef345af519fbcd855cc2f2a4888142e1c93f8b35d892f0c3f86ebffa09

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page