Serialization Interface

The Signing Interface only signs bytes. To sign other types, the Serializer class provides a dumps/loads interface similar to Python’s json module, which serializes the object to a string then signs that.

Use dumps() to serialize and sign the data:

from itsdangerous.serializer import Serializer
s = Serializer("secret-key")
s.dumps([1, 2, 3, 4])
b'[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo'

Use loads() to verify the signature and deserialize the data.

s.loads('[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo')
[1, 2, 3, 4]

By default, data is serialized to JSON with the built-in json module. This internal serializer can be changed by subclassing.

To record and validate the age of the signature, see Signing With Timestamps. To serialize to a format that is safe to use in URLs, see URL Safe Serialization.

Responding to Failure

Exceptions have helpful attributes which allow you to inspect the payload if the signature check failed. This has to be done with extra care because at that point you know that someone tampered with your data but it might be useful for debugging purposes.

from itsdangerous.serializer import Serializer
from itsdangerous.exc import BadSignature, BadData

s = URLSafeSerializer("secret-key")
decoded_payload = None

try:
    decoded_payload = s.loads(data)
    # This payload is decoded and safe
except BadSignature as e:
    if e.payload is not None:
        try:
            decoded_payload = s.load_payload(e.payload)
        except BadData:
            pass
        # This payload is decoded but unsafe because someone
        # tampered with the signature. The decode (load_payload)
        # step is explicit because it might be unsafe to unserialize
        # the payload (think pickle instead of json!)

If you don’t want to inspect attributes to figure out what exactly went wrong you can also use loads_unsafe():

sig_okay, payload = s.loads_unsafe(data)

The first item in the returned tuple is a boolean that indicates if the signature was correct.

Fallback Signers

You may want to upgrade the signing parameters without invalidating existing signatures immediately. For example, you may decide that you want to use a different digest method. New signatures should use the new method, but old signatures should still validate.

A list of fallback_signers can be given that will be tried if unsigning with the current signer fails. Each item in the list can be:

  • A dict of signer_kwargs to instantiate the signer class passed to the serializer.

  • A Signer class to instantiated with the secret_key, salt, and signer_kwargs passed to the serializer.

  • A tuple of (signer_class, signer_kwargs) to instantiate the given class with the given args.

For example, this is a serializer that signs using SHA-512, but will unsign using either SHA-512 or SHA-1:

s = Serializer(
    signer_kwargs={"digest_method": hashlib.sha512},
    fallback_signers=[{"digest_method": hashlib.sha1}]
)

API

class itsdangerous.serializer.Serializer(secret_key, salt=b'itsdangerous', serializer=None, serializer_kwargs=None, signer=None, signer_kwargs=None, fallback_signers=None)

A serializer wraps a Signer to enable serializing and securely signing data other than bytes. It can unsign to verify that the data hasn’t been changed.

The serializer provides dumps() and loads(), similar to json, and by default uses json internally to serialize the data to bytes.

The secret key should be a random string of bytes and should not be saved to code or version control. Different salts should be used to distinguish signing in different contexts. See General Concepts for information about the security of the secret key and salt.

Parameters
  • secret_key (Union[Iterable[Union[str, bytes]], str, bytes]) – The secret key to sign and verify with. Can be a list of keys, oldest to newest, to support key rotation.

  • salt (Optional[Union[str, bytes]]) – Extra key to combine with secret_key to distinguish signatures in different contexts.

  • serializer (Any) – An object that provides dumps and loads methods for serializing data to a string. Defaults to default_serializer, which defaults to json.

  • serializer_kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass when calling serializer.dumps.

  • signer (Optional[Type[itsdangerous.signer.Signer]]) – A Signer class to instantiate when signing data. Defaults to default_signer, which defaults to Signer.

  • signer_kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass when instantiating the Signer class.

  • fallback_signers (Optional[List[Union[Dict[str, Any], Tuple[Type[itsdangerous.signer.Signer], Dict[str, Any]], Type[itsdangerous.signer.Signer]]]]) – List of signer parameters to try when unsigning with the default signer fails. Each item can be a dict of signer_kwargs, a Signer class, or a tuple of (signer, signer_kwargs). Defaults to default_fallback_signers.

Changelog

Changed in version 2.0: Added support for key rotation by passing a list to secret_key.

Changed in version 2.0: Removed the default SHA-512 fallback signer from default_fallback_signers.

Changed in version 1.1: Added support for fallback_signers and configured a default SHA-512 fallback. This fallback is for users who used the yanked 1.0.0 release which defaulted to SHA-512.

Changed in version 0.14: The signer and signer_kwargs parameters were added to the constructor.

default_fallback_signers: List[Union[Dict[str, Any], Tuple[Type[itsdangerous.signer.Signer], Dict[str, Any]], Type[itsdangerous.signer.Signer]]] = []

The default fallback signers to try when unsigning fails.

default_serializer: Any = <module 'json' from '/usr/lib/python3.10/json/__init__.py'>

The default serialization module to use to serialize data to a string internally. The default is json, but can be changed to any object that provides dumps and loads methods.

default_signer

The default Signer class to instantiate when signing data. The default is itsdangerous.signer.Signer.

alias of itsdangerous.signer.Signer

dump(obj, f, salt=None)

Like dumps() but dumps into a file. The file handle has to be compatible with what the internal serializer expects.

Parameters
  • obj (Any) –

  • f (IO) –

  • salt (Optional[Union[str, bytes]]) –

Return type

None

dump_payload(obj)

Dumps the encoded object. The return value is always bytes. If the internal serializer returns text, the value will be encoded as UTF-8.

Parameters

obj (Any) –

Return type

bytes

dumps(obj, salt=None)

Returns a signed string serialized with the internal serializer. The return value can be either a byte or unicode string depending on the format of the internal serializer.

Parameters
  • obj (Any) –

  • salt (Optional[Union[str, bytes]]) –

Return type

Union[str, bytes]

iter_unsigners(salt=None)

Iterates over all signers to be tried for unsigning. Starts with the configured signer, then constructs each signer specified in fallback_signers.

Parameters

salt (Optional[Union[str, bytes]]) –

Return type

Iterator[itsdangerous.signer.Signer]

load(f, salt=None)

Like loads() but loads from a file.

Parameters
  • f (IO) –

  • salt (Optional[Union[str, bytes]]) –

Return type

Any

load_payload(payload, serializer=None)

Loads the encoded object. This function raises BadPayload if the payload is not valid. The serializer parameter can be used to override the serializer stored on the class. The encoded payload should always be bytes.

Parameters
  • payload (bytes) –

  • serializer (Optional[Any]) –

Return type

Any

load_unsafe(f, salt=None)

Like loads_unsafe() but loads from a file.

Changelog

New in version 0.15.

Parameters
  • f (IO) –

  • salt (Optional[Union[str, bytes]]) –

Return type

Tuple[bool, Any]

loads(s, salt=None, **kwargs)

Reverse of dumps(). Raises BadSignature if the signature validation fails.

Parameters
  • s (Union[str, bytes]) –

  • salt (Optional[Union[str, bytes]]) –

  • kwargs (Any) –

Return type

Any

loads_unsafe(s, salt=None)

Like loads() but without verifying the signature. This is potentially very dangerous to use depending on how your serializer works. The return value is (signature_valid, payload) instead of just the payload. The first item will be a boolean that indicates if the signature is valid. This function never fails.

Use it for debugging only and if you know that your serializer module is not exploitable (for example, do not use it with a pickle serializer).

Changelog

New in version 0.15.

Parameters
  • s (Union[str, bytes]) –

  • salt (Optional[Union[str, bytes]]) –

Return type

Tuple[bool, Any]

make_signer(salt=None)

Creates a new instance of the signer to be used. The default implementation uses the Signer base class.

Parameters

salt (Optional[Union[str, bytes]]) –

Return type

itsdangerous.signer.Signer

property secret_key: bytes

The newest (last) entry in the secret_keys list. This is for compatibility from before key rotation support was added.

secret_keys: List[bytes]

The list of secret keys to try for verifying signatures, from oldest to newest. The newest (last) key is used for signing.

This allows a key rotation system to keep a list of allowed keys and remove expired ones.