Sign and load URL-safe values
To securely pass data through a URL, itsdangerous provides the URLSafeSerializer class. This class serializes data into a format that uses only URL-safe characters—specifically alphanumeric characters, underscores, dashes, and dots—while signing the payload to prevent tampering.
The following example demonstrates how to initialize a URLSafeSerializer with a secret key, sign a dictionary, and verify the result.
from itsdangerous import URLSafeSerializer
auth_serializer = URLSafeSerializer("secret-key-1234")
original_data = {"user_id": 42, "role": "admin"}
signed_token = auth_serializer.dumps(original_data)
restored_data = auth_serializer.loads(signed_token)
assert restored_data == original_data
Core Behavior
The URLSafeSerializer combines several steps into its dumps and loads operations:
- Serialization: By default, it uses a compact JSON representation for the payload.
- Compression: It automatically applies
zlibcompression if the compressed result is smaller than the original JSON string. - Encoding: The resulting bytes are encoded using a URL-safe base64 variant.
- Signing: A cryptographic signature is appended to the encoded payload using the provided
secret_key.
When calling loads, itsdangerous first verifies the signature. If the signature matches, it reverses the encoding and compression steps to return the original Python object. If the payload has been tampered with or the signature is otherwise invalid, the process fails to ensure data integrity.