Django: 数据签名 / itsdangerous JSONWebSignatureSerializer TimedJSONWebSignatureSerializer 已弃用
Protecting complex data structures¶
If you wish to protect a list, tuple or dictionary you can do so using the Signer.sign_object()
and unsign_object()
methods, or signing module’s dumps()
or loads()
functions (which are shortcuts for TimestampSigner(salt='django.core.signing').sign_object()/unsign_object()
). These 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:
>>> from django.core import signing
>>> signer = signing.TimestampSigner()
>>> value = signer.sign_object({'foo': 'bar'})
>>> value
'eyJmb28iOiJiYXIifQ:1kx6R3:D4qGKiptAqo5QW9iv4eNLc6xl4RwiFfes6oOcYhkYnc'
>>> signer.unsign_object(value)
{'foo': 'bar'}
>>> value = signing.dumps({'foo': 'bar'})
>>> value
'eyJmb28iOiJiYXIifQ:1kx6Rf:LBB39RQmME-SRvilheUe5EmPYRbuDBgQp2tCAi7KGLk'
>>> signing.loads(value)
{'foo': 'bar'}
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 signing.loads(object)
:
>>> from django.core import signing >>> value = signing.dumps(('a','b','c')) >>> signing.loads(value) ['a', 'b', 'c']
dumps
(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)[source]¶- Returns URL-safe, signed base64 compressed JSON string. Serialized object is signed using
TimestampSigner
.
loads
(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None)[source]¶- Reverse of
dumps()
, raisesBadSignature
if signature fails. Checksmax_age
(in seconds) if given.
Changed in Django 3.2:The
sign_object()
andunsign_object()
methods were added.
Version 2.0.0
Released 2021-05-11
- Drop support for Python 2 and 3.5.
- JWS support (
JSONWebSignatureSerializer
,TimedJSONWebSignatureSerializer
) is deprecated. Use a dedicated JWS/JWT library such as authlib instead. #129 - Importing
itsdangerous.json
is deprecated. Import Python’sjson
module instead. #152 - Simplejson is no longer used if it is installed. To use a different library, pass it as
Serializer(serializer=...)
. #146