Skip to main content

Sign and load URL-safe values

To sign and verify data for use in URLs, itsdangerous provides the URLSafeSerializer class. This serializer ensures that the resulting string contains only characters safe for URL parameters (alphanumeric characters, underscores, hyphens, and dots) while cryptographically signing the payload to prevent tampering.

The URLSafeSerializer uses a secret key to generate a signature. When you call dumps, it serializes the data (typically to JSON), optionally compresses it using zlib if the compressed version is smaller, and then encodes it using a URL-safe base64 format. The loads method reverses this process, verifying the signature before decoding and decompressing the data.

from itsdangerous import URLSafeSerializer

# Initialize the serializer with a fixed secret key
auth_serializer = URLSafeSerializer("secret-key-for-signing")

# Define a small dictionary to serialize
user_data = {"user_id": 42, "status": "active"}

# Serialize the dictionary into a URL-safe signed string
signed_url_token = auth_serializer.dumps(user_data)

# Restore the original data 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

Signature Verification​

The URLSafeSerializer ensures data integrity by appending a cryptographic signature to the payload. If the signed_url_token is modified by a third party, the loads method will detect the mismatch and raise an exception, preventing the application from processing tampered data.

Automatic Compression​

The URLSafeSerializerMixin logic within URLSafeSerializer automatically attempts to compress the serialized payload using zlib. If the compressed data is at least one byte smaller than the original JSON string, the serializer uses the compressed version and prefixes the base64 output with a dot (.) to signal that decompression is required during the loads operation.