Sign and load URL-safe values
When you need to pass signed data through a URL, standard cryptographic signatures often contain characters that require percent-encoding. The URLSafeSerializer in itsdangerous solves this by producing strings composed only of alphanumeric characters, underscores, hyphens, and dots.
To sign and verify data for use in URLs, instantiate URLSafeSerializer with a secret key, then use dumps to create the signed string and loads to retrieve the original value.
from itsdangerous import URLSafeSerializer
# Initialize the serializer with a fixed secret key
auth_serializer = URLSafeSerializer(secret_key=b"correct-horse-battery-staple")
# The data to be signed
user_data = {"user_id": 42, "role": "admin"}
# Serialize the dictionary into a URL-safe signed string
signed_url_token = auth_serializer.dumps(user_data)
# Restore the original dictionary from the signed string
restored_data = auth_serializer.loads(signed_url_token)
# Verify that the restored data matches the original input
assert restored_data == user_data
Observable Behavior
The URLSafeSerializer uses a mixin that modifies the payload handling of the standard serialization process:
- Compression: If the zlib-compressed version of the data is smaller than the original JSON string,
URLSafeSerializerautomatically compresses the payload and prefixes it with a dot (.). - Encoding: The resulting data is encoded using a URL-safe base64 variant, ensuring the output can be used directly in query parameters or path segments without further encoding.
- Verification: The
loadsmethod performs signature verification before decoding. If the signature is invalid or the payload has been tampered with, it raises an exception from theitsdangerous.excmodule.