Skip to main content

JWT token service for Swarmauri

Project description

Swarmauri Logo

PyPI - Downloads Hits PyPI - Python Version PyPI - License PyPI - swarmauri_tokens_jwt


swarmauri_tokens_jwt

A standard JWT token service for the Swarmauri framework. This service implements minting and verifying JSON Web Tokens and exposes a JWKS endpoint for public key discovery.

Installation

Install the service with your preferred Python packaging tool:

pip install swarmauri_tokens_jwt
poetry add swarmauri_tokens_jwt
uv pip install swarmauri_tokens_jwt

Features

  • Mint and verify JWS/JWT tokens backed by any :class:~swarmauri_core.key_providers.IKeyProvider
  • Supports algorithms like HS256, RS256, ES256, PS256 and EdDSA
  • Adds standard temporal claims (iat, nbf, and optional exp) plus issuer, subject, audience and scope defaults when minting tokens
  • Validates expiration, not-before, issuer and audience claims during verification
  • Publishes a JWKS endpoint for public key discovery through your key provider
  • Install the optional cryptography dependency to enable RSA, ECDSA and EdDSA signing keys

Usage

JWTTokenService requires an asynchronous IKeyProvider to supply signing material. The example below shows how to mint and verify a symmetric HS256 token using a minimal in-memory key provider.

import asyncio
import base64
from swarmauri_tokens_jwt import JWTTokenService
from swarmauri_core.key_providers import (
    ExportPolicy,
    IKeyProvider,
    KeyRef,
    KeyUse,
)
from swarmauri_core.crypto.types import JWAAlg, KeyType


class InMemoryKeyProvider(IKeyProvider):
    def __init__(self) -> None:
        self.secret = b"secret"
        self.kid = "sym"
        self.version = 1

    def supports(self) -> dict[str, list[str]]:
        return {}

    async def create_key(self, spec):
        raise NotImplementedError

    async def import_key(self, spec, material, *, public=None):
        raise NotImplementedError

    async def rotate_key(self, kid, *, spec_overrides=None):
        raise NotImplementedError

    async def destroy_key(self, kid, version=None) -> bool:
        return False

    async def get_key(self, kid, version=None, *, include_secret=False) -> KeyRef:
        material = self.secret if include_secret else None
        return KeyRef(
            kid=self.kid,
            version=self.version,
            type=KeyType.OPAQUE,
            uses=(KeyUse.SIGN,),
            export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
            material=material,
        )

    async def list_versions(self, kid):
        return (self.version,)

    async def get_public_jwk(self, kid, version=None):
        return {}

    async def jwks(self) -> dict:
        k = base64.urlsafe_b64encode(self.secret).rstrip(b"=").decode()
        return {"keys": [{"kty": "oct", "kid": f"{self.kid}.{self.version}", "k": k}]}

    async def random_bytes(self, n: int) -> bytes:
        return b"\x00" * n

    async def hkdf(self, ikm: bytes, *, salt: bytes, info: bytes, length: int) -> bytes:
        return b"\x00" * length


async def main() -> None:
    svc = JWTTokenService(InMemoryKeyProvider(), default_issuer="issuer")
    token = await svc.mint(
        {"sub": "alice"},
        alg=JWAAlg.HS256,
        kid="sym",
        lifetime_s=600,  # override the default one-hour lifetime if needed
    )
    claims = await svc.verify(token, issuer="issuer")
    assert claims["sub"] == "alice"


asyncio.run(main())

verify retrieves the JSON Web Key Set from the provider and enforces expiration, not-before, issuer and audience checks before returning the decoded claims. Expose the service's :meth:jwks coroutine to publish the active public keys from your provider.

The service also supports asymmetric algorithms such as RS256, ES256 and EdDSA when the key provider exposes the appropriate keys. See the docstrings in :mod:swarmauri_tokens_jwt for additional details on the API surface.

Want to help?

If you want to contribute to swarmauri-sdk, read up on our guidelines for contributing that will help you get started.

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

swarmauri_tokens_jwt-0.3.0.dev31.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

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

swarmauri_tokens_jwt-0.3.0.dev31-py3-none-any.whl (10.7 kB view details)

Uploaded Python 3

File details

Details for the file swarmauri_tokens_jwt-0.3.0.dev31.tar.gz.

File metadata

  • Download URL: swarmauri_tokens_jwt-0.3.0.dev31.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.3 {"installer":{"name":"uv","version":"0.10.3","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":true}

File hashes

Hashes for swarmauri_tokens_jwt-0.3.0.dev31.tar.gz
Algorithm Hash digest
SHA256 fa9c33b8dc71a11702d2f24774c1132d4104c8458d3daa94938387129cc6140c
MD5 5c62f58bfbe98e8d6f9506ea07b5dd72
BLAKE2b-256 7436fb909c5d0b9992649b33b60ff5d820ea3731db28521b5f1b55d41b7f0726

See more details on using hashes here.

File details

Details for the file swarmauri_tokens_jwt-0.3.0.dev31-py3-none-any.whl.

File metadata

  • Download URL: swarmauri_tokens_jwt-0.3.0.dev31-py3-none-any.whl
  • Upload date:
  • Size: 10.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.3 {"installer":{"name":"uv","version":"0.10.3","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":true}

File hashes

Hashes for swarmauri_tokens_jwt-0.3.0.dev31-py3-none-any.whl
Algorithm Hash digest
SHA256 d1a6b04766351d7960abbd2122c2189b15b9dd17f82f0a9d2c8e4c9f510c876c
MD5 270dd0074344cbd893ff4a126ac06bab
BLAKE2b-256 cff0e573a20ff3ef1a48caf72bb1ae9d3a9e2801e973150d0ab02e69111298b0

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