Skip to main content

Python package for managing authentication keys based on python.

Project description

HYAP Auth Manager: Python Authentication Framework for Asymmetrics and Symmetrics Keys

banner

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.

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
    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")}

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

hyap_auth_manager-0.0.1.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.

hyap_auth_manager-0.0.1-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file hyap_auth_manager-0.0.1.tar.gz.

File metadata

  • Download URL: hyap_auth_manager-0.0.1.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.10.16

File hashes

Hashes for hyap_auth_manager-0.0.1.tar.gz
Algorithm Hash digest
SHA256 d51baa319aab330ca85020398edc511dcd02827c11b0c204dca50b6f823294f0
MD5 16681c0e67469264e326e1b338f03851
BLAKE2b-256 28e066c8efd97b0e23dd82bff2abc91312ead28bc3f0f5939e3d00602c543240

See more details on using hashes here.

File details

Details for the file hyap_auth_manager-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for hyap_auth_manager-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c78d40ba18a991ee32bf8592751f7e7577766ce4bd95cb0a26009c51e1aa0bca
MD5 d3e8915b4f6d4da2315e8404deed6308
BLAKE2b-256 396be1a7138d9924cb3bf1b8ca111ea98a77c0b68c706a510b48a6517955dfc8

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