Django’s signing methods live in the
django.core.signing module. To sign a value, first instantiate a
The signature is appended to the end of the string, following the colon. You can retrieve the original value using the
If the signature or value have been altered in any way, a
django.core.signing.BadSignature exception will be raised:
By default, the
Signer class uses the
SECRET_KEY setting to generate signatures. You can use a different secret by passing it to the
Returns a signer which uses
key to generate signatures and
sep to separate values.
sep cannot be in the URL safe base64 alphabet. This alphabet contains alphanumeric characters, hyphens, and underscores.
Using The Salt Argument
If you do not wish for every occurrence of a particular string to have the same signature hash, you can use the optional
salt argument to the
Signer class. Using a salt will seed the signing hash function with both the salt and your
Using salt in this way puts the different signatures into different namespaces. A signature that comes from one namespace (a particular salt value) cannot be used to validate the same plaintext string in a different namespace that is using a different salt setting. The result is to prevent an attacker from using a signed string generated in one place in the code as input to another piece of code that is generating (and verifying) signatures using a different salt.
SECRET_KEY, your salt argument does not need to stay secret.
Verifying Timestamped Values
TimestampSigner is a subclass of
Signer that appends a signed timestamp to the value. This allows you to confirm that a signed value was created within a specified period of time:
unsign(value, max_age=None) checks if
value was signed less than
max_age seconds ago, otherwise raises
max_age parameter can accept an integer or a
Protecting Complex Data Structures
If you wish to protect a list, tuple or dictionary you can do so using the signing module’s
loads functions. These imitate Python’s pickle module, but use JSON serialization under the hood. JSON ensures that even if your
SECRET_KEY is stolen an attacker will not be able to execute arbitrary commands by exploiting the pickle format:
Because of the nature of JSON (there is no native distinction between lists and tuples) if you pass in a tuple, you will get a list from
django.middleware.security.SecurityMiddleware provides several security enhancements to the request/response cycle. Each one can be independently enabled or disabled with a setting.
For more on security headers and these settings, see Chapter 17.
In the next chapter we will expand on the quick install guide from Chapter 1 and look at some additional installation and configuration options for Django.