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.1.tar.gz (6.8 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.1-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ulfblk_auth-0.1.1.tar.gz
  • Upload date:
  • Size: 6.8 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.1.tar.gz
Algorithm Hash digest
SHA256 f8d1502c1396651e9be5289c6cbd8311396e43cc9f904a38d31d80872c48b918
MD5 a122311d7e3cc4d6600efda6075f33d4
BLAKE2b-256 c7e4501eb9c0d2ced57a469ac370114d913097d31d419b365dcf9ddc70ca5516

See more details on using hashes here.

File details

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

File metadata

  • Download URL: ulfblk_auth-0.1.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7b5d2a07d79523e318b7ccf0af3d43270dab405f43e3b6b4b95568dcfb55a0c8
MD5 339898719022376631874d82448bac35
BLAKE2b-256 a9cc8c75f6e7f23d6b823e60f187a13d5d4c8ca49583e093fdaf3ed04bf52ce8

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