Skip to main content

Plug-and-play JWT authentication SDK for Flask and FastAPI

Project description

Simple Auth JWT

A simple, plug-and-play JWT authentication SDK for Python web frameworks like Flask and FastAPI. This SDK provides easy-to-use functions for user authentication, token generation, and middleware for protecting routes.

Features

  • JWT token generation (access and refresh tokens)
  • Password hashing and verification
  • Middleware for FastAPI and Flask to protect routes
  • Programmatic configuration
  • Lightweight and easy to integrate

Installation

Install the package via pip:

pip install simple-auth-jwt

Or from source:

git clone https://github.com/omariscode/simple-auth-jwt.git
cd simple-auth-jwt
pip install .

Quick Start

1. Configure the SDK

Configure your JWT settings programmatically:

from simple_auth_jwt import configure

configure(
    secret_key="your-secret-key-here",
    access_expire_min=30,
    refresh_expire_days=7
)

2. Initialize the SDK

First, you need to provide a user repository that implements a get_by_email(email) method returning a user object with email and password attributes.

from simple_auth_jwt import init, login

# Example user repository (you should implement this)
class UserRepository:
    def get_by_email(self, email):
        # Your logic to fetch user from database
        # Return user object with email and password (hashed)
        pass

# Initialize with your repository
init(UserRepository())

3. Login and Get Tokens

# Login user
tokens = login("user@example.com", "password123")
print(tokens)
# Output: {"access": "jwt_access_token", "refresh": "jwt_refresh_token"}

Usage with FastAPI

Protect Routes with Middleware

from fastapi import FastAPI
from simple_auth_jwt.middlewares.fastapi import auth_middleware

app = FastAPI()

# Add middleware to protect all routes
app.middleware("http")(auth_middleware)

@app.get("/protected")
def protected_route():
    return {"message": "This is protected!"}

Full FastAPI Example

from fastapi import FastAPI, HTTPException
from simple_auth_jwt import init, login
from simple_auth_jwt.middlewares.fastapi import auth_middleware

# Initialize SDK
class UserRepo:
    def get_by_email(self, email):
        # Implement your user fetching logic
        return User(email=email, password=hashed_password)

init(UserRepo())

app = FastAPI()
app.middleware("http")(auth_middleware)

@app.post("/login")
def login_endpoint(email: str, password: str):
    try:
        tokens = login(email, password)
        return tokens
    except ValueError:
        raise HTTPException(401, "Invalid credentials")

@app.get("/protected")
def protected():
    return {"data": "secret"}

Usage with Flask

Protect Routes with Middleware

from flask import Flask
from simple_auth_jwt.middlewares.flask import auth_middleware

app = Flask(__name__)

@app.route("/protected")
@auth_middleware
def protected_route():
    return {"message": "This is protected!"}

Note: The Flask is a decorator.

Full Flask Example

from flask import Flask, request, jsonify
from simple_auth_jwt import init, login

# Initialize SDK
class UserRepo:
    def get_by_email(self, email):
        # Implement your user fetching logic
        return User(email=email, password=hashed_password)

init(UserRepo())

app = Flask(__name__)

@app.route("/login", methods=["POST"])
def login_endpoint():
    data = request.get_json()
    try:
        tokens = login(data["email"], data["password"])
        return jsonify(tokens)
    except ValueError:
        return jsonify({"error": "Invalid credentials"}), 401

# Add protection as needed.

Configuration

Configure the SDK using the configure function with the following parameters:

  • secret_key: Secret key for JWT signing (default: "change-me")
  • access_expire_min: Access token expiration in minutes (default: 30)
  • refresh_expire_days: Refresh token expiration in days (default: 7)

Example:

from simple_auth_jwt import configure

configure(secret_key="my-secret", access_expire_min=60)

API Reference

configure(**kwargs)

Configure the SDK settings.

  • secret_key: Secret key for JWT signing
  • access_expire_min: Access token expiration in minutes
  • refresh_expire_days: Refresh token expiration in days

init(user_repository)

Initialize the SDK with a user repository.

  • user_repository: Object with get_by_email(email) method

login(email, password)

Authenticate a user and return JWT tokens.

  • email: User's email
  • password: User's password
  • Returns: Dict with "access" and "refresh" tokens

Middlewares

  • simple_auth_jwt.middlewares.fastapi.auth_middleware: FastAPI middleware for token verification
  • simple_auth_jwt.middlewares.flask.auth_middleware: Flask middleware for token verification

Dependencies

  • passlib[bcrypt]: For password hashing
  • python-jose: For JWT handling
  • fastapi: For FastAPI integration
  • flask: For Flask integration

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

MIT License

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

simple_auth_jwt-0.2.2.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

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

simple_auth_jwt-0.2.2-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file simple_auth_jwt-0.2.2.tar.gz.

File metadata

  • Download URL: simple_auth_jwt-0.2.2.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for simple_auth_jwt-0.2.2.tar.gz
Algorithm Hash digest
SHA256 cd85e4d35008ef2696d491624b6551245b05344d5add03ea5cad887ed809e8ef
MD5 fcbb8ff738f83c93af9d5e7ffb43e816
BLAKE2b-256 04109f1f5fbea7045999d7de6ba613d11f833e84bf7a40fe1756f29cf0430354

See more details on using hashes here.

File details

Details for the file simple_auth_jwt-0.2.2-py3-none-any.whl.

File metadata

File hashes

Hashes for simple_auth_jwt-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c01c88bb71742da447a89db056b3ad17d91b6d504ef041029bad81970e3069dd
MD5 67637fae05731bbab175184ffdf3c684
BLAKE2b-256 41ad92ef5c5dfb84aa0c0dcc5009fba2712e494bc57e43767c0f9cb9be4efbe3

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