# **HYAP Auth Manager: Python Authentication Framework for Asymmetrics and Symmetrics Keys**
<p align="center">
<picture>
<img alt="banner" src="./assets/banner.jpg" width=100%>
</picture>
</p>
## **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
1. Clone Repository
```
git clone https://github.com/hanifabd/hyap-auth-manager
```
2. Installation
```
cd hyap-auth-manager && pip install .
```
### Installation Using Pip
1. Installation
```sh
pip install hyap-auth-manager
```
### **Asymmetrics Key Usage | [Example Keys](./tests/keys/) | [Fastapi Example](./tests/test-api-asymmetrics.py)**
**Standar Usage Example**
```py
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**
```py
# 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](./tests/test-api-symmetrics.py)**
**Standar Usage Example**
```py
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**
```py
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")}
```
Raw data
{
"_id": null,
"home_page": "https://github.com/hanifabd/hyap-auth-manager",
"name": "hyap-auth-manager",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "auth, authentication, access, key, web, asymmetrics, symmetrics",
"author": "Hanif Yuli Abdillah P",
"author_email": "hanifabd23@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/05/3f/b314269bbde8a396ac4a40f00c07a527ff8ed6b1e5eaf1a9e2157a852599/hyap_auth_manager-0.0.4.tar.gz",
"platform": null,
"description": "# **HYAP Auth Manager: Python Authentication Framework for Asymmetrics and Symmetrics Keys**\n\n<p align=\"center\">\n <picture>\n <img alt=\"banner\" src=\"./assets/banner.jpg\" width=100%>\n </picture>\n</p>\n\n## **About**\nHYAP 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.\n\n## **Requirements**\n- Python 3.7 or Higher\n- cryptography\n- pyjwt\n\n## **Key Features**\n\n- **JWT Generation**: Securely create JWT tokens with customizable payloads.\n- **JWT Validation**: Easily verify the authenticity of JWT tokens, ensuring that they haven't been tampered with.\n- **Token Expiration**: Set custom expiration times for tokens to ensure they are valid for a specific duration.\n- **Asymmetrics and Symmetrics Support**: Supports both symmetric (HMAC) and asymmetric (RSA) signing algorithms for token generation and validation.\n\n|Algorithm|Type|Key Type|Hash Function|\n|---|---|---|---|\n|HS256|HMAC (Symmetric)|Secret Key|SHA-256|\n|RS256|RSA (Asymmetric)|Public/Private Key|SHA-256|\n|RS384|RSA (Asymmetric)|Public/Private Key|SHA-384|\n|RS512|RSA (Asymmetric)|Public/Private Key|SHA-512|\n|ES256|ECDSA (Asymmetric)|Public/Private Key|SHA-256|\n|ES384|ECDSA (Asymmetric)|Public/Private Key|SHA-384|\n|ES512|ECDSA (Asymmetric)|Public/Private Key|SHA-512|\n|PS256|RSASSA-PSS (Asymmetric)|Public/Private Key|SHA-256|\n|PS384|RSASSA-PSS (Asymmetric)|Public/Private Key|SHA-384|\n|PS512|RSASSA-PSS (Asymmetric)|Public/Private Key|SHA-512|\n\n## Usage\n### Manual Installation via Github\n1. Clone Repository\n ```\n git clone https://github.com/hanifabd/hyap-auth-manager\n ```\n2. Installation\n ```\n cd hyap-auth-manager && pip install .\n ```\n### Installation Using Pip\n1. Installation\n ```sh\n pip install hyap-auth-manager\n ```\n\n### **Asymmetrics Key Usage | [Example Keys](./tests/keys/) | [Fastapi Example](./tests/test-api-asymmetrics.py)**\n**Standar Usage Example**\n```py\nimport json\nfrom hyap_auth_manager.AsymmetricsKeysManager import AsymmetricsKeysManager\n\n# Initialize Asymmetrics Manager\nkey_manager = AsymmetricsKeysManager(algorithm=\"RS256\", output_dir=\"./keys\")\n\n# Generate Keys (Private and Public)\npath = key_manager.generate_keys()\nprint(json.dumps(path, indent=2))\n\n# Read Keys\nprivate_key_val = key_manager.read_keys(\"PRIVATE\")\npublic_key_val = key_manager.read_keys(\"PUBLIC\")\nprint(private_key_val)\nprint(public_key_val)\n\n# Create Access Token\naccess_token = key_manager.generate_access_token(\n PRIVATE_KEY=private_key_val, \n data={\"username\": \"bambang\"},\n expires_delta=30, # in minutes\n)\nprint(json.dumps(access_token, indent=2))\n\n# Check Access Token\ntoken_status = key_manager.check_access_token(\n PUBLIC_KEY=public_key_val,\n token=access_token.get(\"token\").split(\"Bearer \")[1]\n)\nprint()\nprint(token_status)\n```\n**Fastapi Example**\n```py\n# Fastapi Example\nfrom fastapi import FastAPI, Depends, HTTPException, status, Header\nfrom pydantic import BaseModel\nfrom hyap_auth_manager.AsymmetricsKeysManager import AsymmetricsKeysManager\n\napp = FastAPI()\n\n# Models\nclass TokenData(BaseModel):\n username: str\n\nclass User(BaseModel):\n username: str\n password: str\n\n# Fake database for user credentials\nfake_users_db = {\n \"bambang1\": {\"username\": \"bambang1\", \"password\": \"bambangpass1\"},\n}\n\n# Helper Functions\nkey_manager = AsymmetricsKeysManager(algorithm=\"RS256\", output_dir=\"../tests/keys\")\nprivate_key_val = key_manager.read_keys(\"PRIVATE\")\npublic_key_val = key_manager.read_keys(\"PUBLIC\")\n\n# Routes\n@app.post(\"/login\")\ndef login(user: User):\n # Check user and password\n user_data = fake_users_db.get(user.username)\n if not user_data or user_data[\"password\"] != user.password:\n raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=\"Invalid credentials\")\n \n # Create a JWT token with the username as the payload\n token = key_manager.generate_access_token(PRIVATE_KEY=private_key_val, data={\"username\": user.username}, expires_delta=15)\n return {\"access_token\": token}\n\n# Token authentication function\ndef token_authenticator(\n authorization: str = Header(...), # Extract Authorization header\n public_key: str = Depends(lambda: public_key_val), \n auth_service: AsymmetricsKeysManager = Depends()\n) -> dict:\n # Extract the token from the Authorization header\n token = authorization.split(\" \")[1] # Bearer token extraction\n \n # Check if the token is valid using the public key\n result = auth_service.check_access_token(PUBLIC_KEY=public_key, token=token)\n if \"error\" in result:\n # Raise HTTPException if there is an error in the token\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=result[\"error\"],\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n return result\n\n@app.get(\"/protected\")\ndef protected_route(token: dict = Depends(token_authenticator)):\n # If token is valid, return the protected message\n print(token)\n return {\"message\": \"Access granted\", \"user\": token.get(\"data\").get(\"username\")}\n```\n\n---\n\n### **Symmetrics Key Usage | [Fastapi Example](./tests/test-api-symmetrics.py)**\n**Standar Usage Example**\n```py\nimport json\nfrom hyap_auth_manager.SymmetricsKeysManager import SymmetricsKeysManager\n\n# Initialize Symmetrics Manager\nkey_manager = SymmetricsKeysManager(secret_key=\"example-secret-keys-here\")\n\n# Create Access Token\naccess_token = key_manager.generate_access_token(\n data={\"username\": \"bambang\"},\n expires_delta=0, # in minutes\n)\nprint(json.dumps(access_token, indent=2))\n\n# Check Access Token\ntoken_status = key_manager.check_access_token(\n token=access_token.get(\"token\").split(\"Bearer \")[1]\n)\nprint()\nprint(token_status)\n```\n**Fastapi Example**\n```py\nfrom fastapi import FastAPI, Depends, HTTPException, status, Header\nfrom pydantic import BaseModel\nfrom hyap_auth_manager.SymmetricsKeysManager import SymmetricsKeysManager\n\napp = FastAPI()\n\n# Models\nclass TokenData(BaseModel):\n username: str\n\nclass User(BaseModel):\n username: str\n password: str\n\nfake_users_db = {\n \"bambang1\": {\"username\": \"bambang1\", \"password\": \"bambangpass1\"},\n}\n\n# Helper Functions\nkey_manager = SymmetricsKeysManager(secret_key=\"example-secret-keys-here\")\n\n# Routes\n@app.post(\"/login\")\ndef login(user: User):\n # Check user and password\n print(fake_users_db.get(user.username))\n user_data = fake_users_db.get(user.username)\n if not user_data or user_data[\"password\"] != user.password:\n raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=\"Invalid credentials\")\n \n # Create a JWT token with the username as the payload\n token = key_manager.generate_access_token(data={\"username\": user.username}, expires_delta=15)\n return {\"access_token\": token, \"token_type\": \"bearer\"}\n\n# Override key_manager check access token function\ndef token_authenticator(authorization: str = Header(None)) -> dict:\n if authorization is None:\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Authorization header missing\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n \n token = authorization.split(\"Bearer \")[-1]\n \n result = key_manager.check_access_token(token)\n if \"error\" in result:\n # Raise HTTPException if there is an error in the token\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=result[\"error\"],\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n return result\n\n@app.get(\"/protected\")\ndef protected_route(token: dict = Depends(token_authenticator)):\n # If token is valid, return the protected message\n return {\"message\": \"Access granted\", \"user\": token.get(\"data\").get(\"username\")}\n```\n",
"bugtrack_url": null,
"license": null,
"summary": "Python package for managing authentication keys based on python.",
"version": "0.0.4",
"project_urls": {
"Homepage": "https://github.com/hanifabd/hyap-auth-manager",
"Repository": "https://github.com/hanifabd/hyap-auth-manager"
},
"split_keywords": [
"auth",
" authentication",
" access",
" key",
" web",
" asymmetrics",
" symmetrics"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "6734e8b731b901826c6f034b27cdce5eed27579d8ce2f454bbd7a301b61a9250",
"md5": "f12e14229da25e480276c5e04d153a21",
"sha256": "cd732be36541b4eb5af5b3d72de0de7508f4492da09b2b5a2b5a3ac8f85b07e1"
},
"downloads": -1,
"filename": "hyap_auth_manager-0.0.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "f12e14229da25e480276c5e04d153a21",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 8345,
"upload_time": "2025-01-03T04:22:47",
"upload_time_iso_8601": "2025-01-03T04:22:47.768450Z",
"url": "https://files.pythonhosted.org/packages/67/34/e8b731b901826c6f034b27cdce5eed27579d8ce2f454bbd7a301b61a9250/hyap_auth_manager-0.0.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "053fb314269bbde8a396ac4a40f00c07a527ff8ed6b1e5eaf1a9e2157a852599",
"md5": "23658ced2ceb9332a5def7e29fd1a5d7",
"sha256": "ff1a2702e6312051ca8ca14aa3ff499d70e2f2dcaa473d47c459b78280293728"
},
"downloads": -1,
"filename": "hyap_auth_manager-0.0.4.tar.gz",
"has_sig": false,
"md5_digest": "23658ced2ceb9332a5def7e29fd1a5d7",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 6033,
"upload_time": "2025-01-03T04:22:49",
"upload_time_iso_8601": "2025-01-03T04:22:49.638418Z",
"url": "https://files.pythonhosted.org/packages/05/3f/b314269bbde8a396ac4a40f00c07a527ff8ed6b1e5eaf1a9e2157a852599/hyap_auth_manager-0.0.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-01-03 04:22:49",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "hanifabd",
"github_project": "hyap-auth-manager",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "hyap-auth-manager"
}