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 signingaccess_expire_min: Access token expiration in minutesrefresh_expire_days: Refresh token expiration in days
init(user_repository)
Initialize the SDK with a user repository.
user_repository: Object withget_by_email(email)method
login(email, password)
Authenticate a user and return JWT tokens.
email: User's emailpassword: User's password- Returns: Dict with "access" and "refresh" tokens
Middlewares
simple_auth_jwt.middlewares.fastapi.auth_middleware: FastAPI middleware for token verificationsimple_auth_jwt.middlewares.flask.auth_middleware: Flask middleware for token verification
Dependencies
passlib[bcrypt]: For password hashingpython-jose: For JWT handlingfastapi: For FastAPI integrationflask: 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file simple_auth_jwt-0.2.3.tar.gz.
File metadata
- Download URL: simple_auth_jwt-0.2.3.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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9f6e4f4257354f9572550a49dd03d11df7bee57905344a769af2a0c8f16d2f9e
|
|
| MD5 |
58a3114f07ddb7880bfc2eeb0e4abf67
|
|
| BLAKE2b-256 |
5754fd2c3540b3d99749480cfaa2e58b3cf32c183161d1fc6cd0f76462a29466
|
File details
Details for the file simple_auth_jwt-0.2.3-py3-none-any.whl.
File metadata
- Download URL: simple_auth_jwt-0.2.3-py3-none-any.whl
- Upload date:
- Size: 5.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
664c759aec9378e347d1d0dd72fafeb3dbcd2113da2ddae184f632f0a5ad4fe3
|
|
| MD5 |
25f2b38d6afe0e1dcf9932fe5c6b4b9e
|
|
| BLAKE2b-256 |
ced0fc3565afdf052ea6592b3944be780556a99e92f023724972dc0e3b502f59
|