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
Release files for simple-auth-jwt 0.2.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| simple_auth_jwt-0.2.3.tar.gz | 5.6 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| simple_auth_jwt-0.2.3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 11.4 kB
Release files / simple_auth_jwt-0.2.3.tar.gz
| Download URL | simple_auth_jwt-0.2.3.tar.gz |
|---|---|
| Size | 5.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9f6e4f4257354f9572550a49dd03d11df7bee57905344a769af2a0c8f16d2f9e
|
|
BLAKE2b-256 checksum How to use checksums |
5754fd2c3540b3d99749480cfaa2e58b3cf32c183161d1fc6cd0f76462a29466
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|
Release files / simple_auth_jwt-0.2.3-py3-none-any.whl
| Download URL | simple_auth_jwt-0.2.3-py3-none-any.whl |
|---|---|
| Size | 5.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
664c759aec9378e347d1d0dd72fafeb3dbcd2113da2ddae184f632f0a5ad4fe3
|
|
BLAKE2b-256 checksum How to use checksums |
ced0fc3565afdf052ea6592b3944be780556a99e92f023724972dc0e3b502f59
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|