Skip to main content

Detect tampered signed values

When you transmit data to a client and expect it back later, you must ensure the data has not been modified in the interim. If a user changes a signed value—for example, by altering a user ID in a cookie—itsdangerous detects this tampering by comparing the provided signature against a newly generated one.

The Signer class in signer.py provides the core mechanism for this protection. It appends a cryptographic signature to your data, separated by a character (defaulting to .). When you attempt to retrieve the data using unsign, the class splits the value from the signature and verifies the integrity of the payload.

If the signature is missing or does not match the payload, unsign raises a BadSignature exception from exc.py. This exception includes a payload attribute, which contains the data that failed the signature check, allowing for inspection of the tampered content if necessary.

from itsdangerous import BadSignature, Signer

signer = Signer("secret-key")
signed_value = signer.sign(b"fixed-bytes")
assert signer.unsign(signed_value) == b"fixed-bytes"
try:
signer.unsign(b"tampered-value.signature")
except BadSignature:
assert True