Sign and load URL-safe values
To securely serialize Python objects into strings that can be safely used in URLs, itsdangerous provides the URLSafeSerializer class. This class signs the data to prevent tampering and uses a URL-safe base64 encoding, optionally applying zlib compression if it reduces the payload size.
The following example demonstrates how to initialize the serializer with a secret key, sign a dictionary, and verify the result.
from itsdangerous import URLSafeSerializer
# Initialize the serializer with a fixed secret key for signing
auth_serializer = URLSafeSerializer("static-secret-key")
# Define a small dictionary to be serialized
user_data = {"user_id": 42, "role": "admin"}
# Serialize the dictionary into a URL-safe signed string
token = auth_serializer.dumps(user_data)
# Restore the original dictionary from the signed string
restored_data = auth_serializer.loads(token)
# Verify that the restored data matches the original input
assert restored_data == user_data
assert restored_data["user_id"] == 42
Secure Serialization and Loading
The URLSafeSerializer combines cryptographic signing with URL-safe encoding. When dumps() is called, itsdangerous serializes the object (by default using JSON), signs it using the provided secret key, and encodes the result into a string consisting only of alphanumeric characters, underscores, hyphens, and dots.
When loads() is called, the process is reversed:
- The signature is verified against the secret key to ensure the data has not been modified.
- If the payload was compressed during serialization (indicated by a leading dot), it is automatically decompressed.
- The base64-encoded data is decoded and the original Python object is reconstructed.
If the signature is invalid or the data has been tampered with, loads() will raise an exception, ensuring that only data signed by the application is accepted.