PyMacaroons

0.13.0 · active · verified Mon Apr 13

PyMacaroons is a Python implementation of Macaroons, a form of bearer credential similar to cookies but with embedded caveats defining authorization requirements. It is currently at version 0.13.0 and is described as stable with infrequent changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a Macaroon with a first-party caveat, serialize it, and then verify it using a Verifier with appropriate callbacks for key retrieval and caveat satisfaction.

from pymacaroons import Macaroon, Verifier

# Keys for signing macaroons are associated with some identifier for later
# verification. This could be stored in a database, key-value store, memory, etc.
keys = {
    'key-for-bob': 'asdfasdfas-a-very-secret-signing-key'
}

# Construct a Macaroon. The location and identifier will be visible after
# construction, and identify which service and key to use to verify it.
m = Macaroon(
    location='cool-picture-service.example.com',
    identifier='key-for-bob',
    key=keys['key-for-bob']
)

# Add a caveat for the target service
m.add_first_party_caveat('picture_id = bobs_cool_cat.jpg')

# Serialize for transport in a cookie, url, OAuth token, etc
serialized_macaroon = m.serialize()
print(f"Serialized Macaroon: {serialized_macaroon}")

# --- Verification Process ---

# A Verifier needs a callback to lookup keys and discharge caveats.
def get_key_for_identifier(identifier):
    return keys.get(identifier)

def verify_caveat(caveat):
    if caveat == 'picture_id = bobs_cool_cat.jpg':
        # In a real application, you'd check against your actual data/context
        return True
    return False


# Deserialize the macaroon on the receiving service
d = Macaroon.deserialize(serialized_macaroon)

# Create a Verifier instance and register the key lookup and caveat verification callbacks
v = Verifier()
v.satisfy_exact('picture_id = bobs_cool_cat.jpg') # Satisfy first-party caveats directly
v.satisfy_third_party(lambda c: True) # Example: satisfy third-party caveats (not used in this example)

try:
    # Verify the macaroon
    verified = v.verify(d, get_key_for_identifier)
    print(f"Macaroon verified: {verified}")
except Exception as e:
    print(f"Macaroon verification failed: {e}")

view raw JSON →