Sign and load URL-safe values
To securely transport Python objects in URLs, itsdangerous provides the URLSafeSerializer class. This serializer signs data to prevent tampering and encodes the result using a URL-safe base64 alphabet, optionally applying zlib compression to minimize string length.
The URLSafeSerializer produces strings containing only alphanumeric characters, underscores, hyphens, and dots. When loading data, the class verifies the cryptographic signature using a secret key before decoding the payload. If the signature is invalid or the data has been altered, the process fails, ensuring that only trusted data is processed by the application.
from itsdangerous import URLSafeSerializer
# Initialize the serializer with a fixed secret key
auth_serializer = URLSafeSerializer("secret-key", salt="auth-data")
# Define a small dictionary to serialize
user_data = {"user_id": 42, "role": "admin"}
# Serialize the dictionary into a URL-safe signed string
token = auth_serializer.dumps(user_data)
# Restore the dictionary from the signed string and verify the signature
restored_data = auth_serializer.loads(token)
# Assert that the restored data is exactly equal to the original
assert restored_data == user_data
assert restored_data["user_id"] == 42
The dumps method handles the internal transformation of the object into a compact JSON representation, followed by optional compression and base64 encoding. The loads method reverses these steps, performing signature validation as the first step of the restoration process. Using a salt during instantiation is a recommended practice in itsdangerous to ensure that signed strings generated for one purpose cannot be reused in a different context, even if they share the same secret key.