PySETO

1.9.1 · active · verified Thu Apr 16

PySETO is a Python implementation of PASETO (Platform-Agnostic SEcurity TOkens) and PASERK (Platform-Agnostic Serialized Keys). It supports all PASETO versions (v1, v2, v3, and v4) and purposes (local and public), having passed all official tests. The library is currently at version 1.9.1 and maintains a regular release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create and verify a PASETO token using the v4.public protocol for asymmetric signatures. It covers key generation from PEM bytes, encoding a payload with a footer, and decoding/verifying the token. It uses the built-in `json_serializer`/`json_deserializer` for dictionary payloads.

import os
import pyseto
from pyseto import Key

# --- Example for v4.public (Asymmetric Signature) ---
# In a real application, keys should be loaded securely, e.g., from environment variables or a KMS.
# For demonstration, we use hardcoded keys. DO NOT USE IN PRODUCTION AS IS.
# These PEMs are for Ed25519 (v4.public)
private_key_pem = os.environ.get(
    'PSETO_V4_PRIVATE_KEY_PEM',
    b"""-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEILTL+0PfTOIQcn2VPkpxMwf6Gbt9n4UEFDjZ4RuUKjd0
-----END PRIVATE KEY-----
""").encode('utf-8')

public_key_pem = os.environ.get(
    'PSETO_V4_PUBLIC_KEY_PEM',
    b"""-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAHrnbu7wEfAP9cGBOAHHwmH4Wsot1ciXBHwBBXQ4gsaI=
-----END PUBLIC KEY-----
""").encode('utf-8')

# 1. Create a private key for signing
private_key = Key.new(version=4, purpose="public", key=private_key_pem)

# 2. Encode/Sign a PASETO token
payload = {"data": "this is a signed message", "user_id": "123"}
footer = {"kid": "v4-public-key-001"}
token = pyseto.encode(private_key, payload, footer=footer, serializer=pyseto.json_serializer)
print(f"Generated Token: {token.decode()}")

# 3. Create a public key for verification
public_key = Key.new(version=4, purpose="public", key=public_key_pem)

# 4. Decode and verify the token
decoded_token = pyseto.decode(public_key, token, deserializer=pyseto.json_deserializer)

# The payload and footer are accessible as dictionary-like objects if deserializer is used
print(f"Decoded Payload: {decoded_token.payload}")
print(f"Decoded Footer: {decoded_token.footer}")

assert decoded_token.payload['data'] == "this is a signed message"
assert decoded_token.footer['kid'] == "v4-public-key-001"
print("Token verified successfully!")

view raw JSON →