Skip to main content

Authentication and authorization: JWT RS256, RBAC, brute force protection, credential encryption

Project description

ulfblk-auth

Authentication and authorization for FastAPI: JWT RS256, RBAC, brute force protection, and credential encryption.

Part of Bloques Reciclables - an open source ecosystem of reusable code blocks.

Installation

uv add ulfblk-auth
# or
pip install ulfblk-auth

Features

JWT Manager (RS256)

Asymmetric JWT tokens with tenant and role support:

from ulfblk_auth.jwt import JWTManager

jwt_manager = JWTManager(
    private_key=PRIVATE_KEY_PEM,
    public_key=PUBLIC_KEY_PEM,
    access_token_expire_minutes=30,
    refresh_token_expire_days=7,
)

# Create tokens
access_token = jwt_manager.create_access_token(
    user_id="user-123",
    tenant_id="acme",
    roles=["admin"],
    permissions=["users:read", "users:write"],
)

refresh_token = jwt_manager.create_refresh_token(
    user_id="user-123",
    tenant_id="acme",
)

# Decode and validate
token_data = jwt_manager.decode_token(access_token)
# token_data.user_id, token_data.tenant_id, token_data.roles, token_data.permissions

RBAC (Role-Based Access Control)

FastAPI dependency injection for permission and role checks:

from ulfblk_auth.rbac import configure, require_permissions, require_roles, get_current_user

# Configure once at startup
configure(jwt_manager)

# Require specific permissions
@app.delete("/users/{user_id}")
async def delete_user(user=Depends(require_permissions("users:delete"))):
    ...

# Require specific roles
@app.get("/admin/stats")
async def admin_stats(user=Depends(require_roles("admin", "manager"))):
    ...

# Get current user (any authenticated user)
@app.get("/me")
async def me(user=Depends(get_current_user)):
    return {"user_id": user.user_id, "tenant": user.tenant_id}

Brute Force Protection

Storage-agnostic login attempt tracking with account lockout:

from ulfblk_auth.brute_force import BruteForceProtection, LoginAttemptState

protection = BruteForceProtection(max_attempts=5, lockout_minutes=30)

# Check if locked
state = LoginAttemptState()  # load from your storage
if protection.is_locked(state):
    raise HTTPException(status_code=429, detail="Account locked")

# Record attempts
state = protection.record_failed_attempt(state, ip_address="1.2.3.4")
# or on success:
state = protection.record_successful_login(state, ip_address="1.2.3.4")
# persist state to your storage

Credential Encryption (Fernet AES-256)

Encrypt sensitive credentials (API keys, tokens) for storage:

from ulfblk_auth.credentials import CredentialEncryptor

# Generate a key (store securely, e.g., in env vars)
key = CredentialEncryptor.generate_key()

encryptor = CredentialEncryptor(key=key)
encrypted = encryptor.encrypt("sk-my-secret-api-key")
decrypted = encryptor.decrypt(encrypted)

# Key rotation
new_key = CredentialEncryptor.generate_key()
re_encrypted = encryptor.rotate_key(encrypted, new_key)

Dependencies

Requirements

  • Python 3.11+
  • FastAPI 0.115+

License

MIT

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

ulfblk_auth-0.1.0.tar.gz (6.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ulfblk_auth-0.1.0-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file ulfblk_auth-0.1.0.tar.gz.

File metadata

  • Download URL: ulfblk_auth-0.1.0.tar.gz
  • Upload date:
  • Size: 6.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for ulfblk_auth-0.1.0.tar.gz
Algorithm Hash digest
SHA256 3caa8c800f6d0ae05393738953c071f42e66cfd26acf183fe1cd11cafe3d4de5
MD5 5dd99251050323dc94c8f7b1084c9576
BLAKE2b-256 1ffc33f2dd964fcbbdfc93d6a2645b416cf610a57f73b2fd044d0d762074a850

See more details on using hashes here.

File details

Details for the file ulfblk_auth-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: ulfblk_auth-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.11 {"installer":{"name":"uv","version":"0.10.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for ulfblk_auth-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 760a5866ac9e82de6d0793827794bf53f76b28c98d5709024e66a68883133353
MD5 7f6386e44acc50bc96b082a90d88f316
BLAKE2b-256 275acfe01ca9ed0151c057b4a2e295f5f72f9abc08382472ca7ad0fa01b0cd0b

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