HYAP Auth Manager: Python Authentication Framework for Asymmetrics and Symmetrics Keys
About
HYAP Authentication Manager is a lightweight library designed to simplify the generation and verification of JWT (JSON Web Tokens) in your applications. It provides easy-to-use methods for securely creating tokens and validating them, ensuring that authentication processes are smooth and secure.
Requirements
- Python 3.7 or Higher
- cryptography
- pyjwt
Key Features
- JWT Generation: Securely create JWT tokens with customizable payloads.
- JWT Validation: Easily verify the authenticity of JWT tokens, ensuring that they haven't been tampered with.
- Token Expiration: Set custom expiration times for tokens to ensure they are valid for a specific duration.
- Asymmetrics and Symmetrics Support: Supports both symmetric (HMAC) and asymmetric (RSA) signing algorithms for token generation and validation.
| Algorithm | Type | Key Type | Hash Function |
|---|---|---|---|
| HS256 | HMAC (Symmetric) | Secret Key | SHA-256 |
| RS256 | RSA (Asymmetric) | Public/Private Key | SHA-256 |
| RS384 | RSA (Asymmetric) | Public/Private Key | SHA-384 |
| RS512 | RSA (Asymmetric) | Public/Private Key | SHA-512 |
| ES256 | ECDSA (Asymmetric) | Public/Private Key | SHA-256 |
| ES384 | ECDSA (Asymmetric) | Public/Private Key | SHA-384 |
| ES512 | ECDSA (Asymmetric) | Public/Private Key | SHA-512 |
| PS256 | RSASSA-PSS (Asymmetric) | Public/Private Key | SHA-256 |
| PS384 | RSASSA-PSS (Asymmetric) | Public/Private Key | SHA-384 |
| PS512 | RSASSA-PSS (Asymmetric) | Public/Private Key | SHA-512 |
Usage
Manual Installation via Github
- Clone Repository
git clone https://github.com/hanifabd/hyap-auth-manager - Installation
cd hyap-auth-manager && pip install .
Installation Using Pip
- Installation
pip install hyap-auth-manager
Asymmetrics Key Usage | Example Keys | Fastapi Example
Standar Usage Example
import json
from hyap_auth_manager.AsymmetricsKeysManager import AsymmetricsKeysManager
# Initialize Asymmetrics Manager
key_manager = AsymmetricsKeysManager(algorithm="RS256", output_dir="./keys")
# Generate Keys (Private and Public)
path = key_manager.generate_keys()
print(json.dumps(path, indent=2))
# Read Keys
private_key_val = key_manager.read_keys("PRIVATE")
public_key_val = key_manager.read_keys("PUBLIC")
print(private_key_val)
print(public_key_val)
# Create Access Token
access_token = key_manager.generate_access_token(
PRIVATE_KEY=private_key_val,
data={"username": "bambang"},
expires_delta=30, # in minutes
)
print(json.dumps(access_token, indent=2))
# Check Access Token
token_status = key_manager.check_access_token(
PUBLIC_KEY=public_key_val,
token=access_token.get("token").split("Bearer ")[1]
)
print()
print(token_status)
Fastapi Example
# Fastapi Example
from fastapi import FastAPI, Depends, HTTPException, status, Header
from pydantic import BaseModel
from hyap_auth_manager.AsymmetricsKeysManager import AsymmetricsKeysManager
app = FastAPI()
# Models
class TokenData(BaseModel):
username: str
class User(BaseModel):
username: str
password: str
# Fake database for user credentials
fake_users_db = {
"bambang1": {"username": "bambang1", "password": "bambangpass1"},
}
# Helper Functions
key_manager = AsymmetricsKeysManager(algorithm="RS256", output_dir="../tests/keys")
private_key_val = key_manager.read_keys("PRIVATE")
public_key_val = key_manager.read_keys("PUBLIC")
# Routes
@app.post("/login")
def login(user: User):
# Check user and password
user_data = fake_users_db.get(user.username)
if not user_data or user_data["password"] != user.password:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
# Create a JWT token with the username as the payload
token = key_manager.generate_access_token(PRIVATE_KEY=private_key_val, data={"username": user.username}, expires_delta=15)
return {"access_token": token}
# Token authentication function
def token_authenticator(
authorization: str = Header(...), # Extract Authorization header
public_key: str = Depends(lambda: public_key_val),
auth_service: AsymmetricsKeysManager = Depends()
) -> dict:
# Extract the token from the Authorization header
token = authorization.split(" ")[1] # Bearer token extraction
# Check if the token is valid using the public key
result = auth_service.check_access_token(PUBLIC_KEY=public_key, token=token)
if "error" in result:
# Raise HTTPException if there is an error in the token
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=result["error"],
headers={"WWW-Authenticate": "Bearer"},
)
return result
@app.get("/protected")
def protected_route(token: dict = Depends(token_authenticator)):
# If token is valid, return the protected message
print(token)
return {"message": "Access granted", "user": token.get("data").get("username")}
Symmetrics Key Usage | Fastapi Example
Standar Usage Example
import json
from hyap_auth_manager.SymmetricsKeysManager import SymmetricsKeysManager
# Initialize Symmetrics Manager
key_manager = SymmetricsKeysManager(secret_key="example-secret-keys-here")
# Create Access Token
access_token = key_manager.generate_access_token(
data={"username": "bambang"},
expires_delta=0, # in minutes
)
print(json.dumps(access_token, indent=2))
# Check Access Token
token_status = key_manager.check_access_token(
token=access_token.get("token").split("Bearer ")[1]
)
print()
print(token_status)
Fastapi Example
from fastapi import FastAPI, Depends, HTTPException, status, Header
from pydantic import BaseModel
from hyap_auth_manager.SymmetricsKeysManager import SymmetricsKeysManager
app = FastAPI()
# Models
class TokenData(BaseModel):
username: str
class User(BaseModel):
username: str
password: str
fake_users_db = {
"bambang1": {"username": "bambang1", "password": "bambangpass1"},
}
# Helper Functions
key_manager = SymmetricsKeysManager(secret_key="example-secret-keys-here")
# Routes
@app.post("/login")
def login(user: User):
# Check user and password
print(fake_users_db.get(user.username))
user_data = fake_users_db.get(user.username)
if not user_data or user_data["password"] != user.password:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
# Create a JWT token with the username as the payload
token = key_manager.generate_access_token(data={"username": user.username}, expires_delta=15)
return {"access_token": token, "token_type": "bearer"}
# Override key_manager check access token function
def token_authenticator(authorization: str = Header(None)) -> dict:
if authorization is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authorization header missing",
headers={"WWW-Authenticate": "Bearer"},
)
token = authorization.split("Bearer ")[-1]
result = key_manager.check_access_token(token)
if "error" in result:
# Raise HTTPException if there is an error in the token
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=result["error"],
headers={"WWW-Authenticate": "Bearer"},
)
return result
@app.get("/protected")
def protected_route(token: dict = Depends(token_authenticator)):
# If token is valid, return the protected message
return {"message": "Access granted", "user": token.get("data").get("username")}
Metadata
Release files for hyap-auth-manager 0.0.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| hyap_auth_manager-0.0.4.tar.gz | 6.0 kB | Without provenance | Details for hyap_auth_manager-0.0.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| hyap_auth_manager-0.0.4-py3-none-any.whl | Python 3 | none | any | Details for hyap_auth_manager-0.0.4-py3-none-any.whl |
Total release size: 14.4 kB
Release files / hyap_auth_manager-0.0.4.tar.gz
| Download URL | hyap_auth_manager-0.0.4.tar.gz |
|---|---|
| Size | 6.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ff1a2702e6312051ca8ca14aa3ff499d70e2f2dcaa473d47c459b78280293728
|
|
BLAKE2b-256 checksum How to use checksums |
053fb314269bbde8a396ac4a40f00c07a527ff8ed6b1e5eaf1a9e2157a852599
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.0.1 CPython/3.10.16
|
Release files / hyap_auth_manager-0.0.4-py3-none-any.whl
| Download URL | hyap_auth_manager-0.0.4-py3-none-any.whl |
|---|---|
| Size | 8.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cd732be36541b4eb5af5b3d72de0de7508f4492da09b2b5a2b5a3ac8f85b07e1
|
|
BLAKE2b-256 checksum How to use checksums |
6734e8b731b901826c6f034b27cdce5eed27579d8ce2f454bbd7a301b61a9250
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.0.1 CPython/3.10.16
|
Security for hyap-auth-manager 0.0.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.