Skip to main content

Sign and load URL-safe values

To sign and load data into a URL-safe format, use the URLSafeSerializer class. This class ensures that the resulting string contains only characters safe for use in URLs, specifically alphanumeric characters along with _, -, and ..

The following example demonstrates how to initialize the serializer with a secret key, sign a dictionary, 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
signed_token = auth_serializer.dumps(original_data)

# Restore the data and verify the signature
loaded_data = auth_serializer.loads(signed_token)

# Assert that the restored data is exactly equal to the original
assert loaded_data == original_data

Serialization and Verification

The URLSafeSerializer.dumps method converts the input data into a compact, URL-safe string. This process involves serializing the object (typically to JSON), compressing it if beneficial, and appending a cryptographic signature based on the provided secret key.

To retrieve the data, URLSafeSerializer.loads verifies the signature to ensure the content has not been tampered with. If the signature is valid, it reverses the encoding and compression to return the original Python object. If the signature is invalid or the data has been modified, the method raises a validation error.