Skip to main content

Sign and load URL-safe values

To securely pass data through a URL, itsdangerous provides the URLSafeSerializer class. This serializer ensures that the resulting string contains only characters that are safe for use in URLs (alphanumeric characters, underscores, hyphens, and dots) while protecting the integrity of the data with a cryptographic signature.

The following example demonstrates how to initialize a URLSafeSerializer with a secret key, serialize a dictionary into a signed string, and then verify and restore the original data.

from itsdangerous import URLSafeSerializer

# Initialize the serializer with a fixed secret key
auth_serializer = URLSafeSerializer("secret-key")

# Define a small dictionary to be serialized
original_data = {"user_id": 42, "role": "admin"}

# Serialize and sign the data into a URL-safe string
# The dumps method handles JSON serialization, optional compression,
# and base64 encoding.
signed_url_string = auth_serializer.dumps(original_data)

# Restore the data from the signed string
# The loads method verifies the signature before decoding the payload.
restored_data = auth_serializer.loads(signed_url_string)

# Assert that the restored data is exactly equal to the original input
assert restored_data == original_data
assert restored_data["user_id"] == 42

Serialization Behavior

When URLSafeSerializer.dumps is called, itsdangerous performs several steps to ensure the output is compact and safe for transport:

  • The data is serialized to JSON.
  • If the serialized data is smaller when compressed, itsdangerous applies zlib compression.
  • The resulting bytes are signed using the secret_key.
  • The entire package is encoded using URL-safe base64, which replaces standard base64 characters like + and / with - and _, and removes padding.

Verification and Loading

The URLSafeSerializer.loads method reverses this process. It first validates the signature attached to the string. If the signature is invalid or the data has been tampered with, the method raises an itsdangerous.exc.BadSignature exception. Only after successful verification is the payload decoded and deserialized back into its original Python structure.