def test_alt_salt(self, serializer: Serializer, value: Any): signed = serializer.dumps(value, salt="other") with pytest.raises(BadSignature): serializer.loads(signed) assert serializer.loads(signed, salt="other") == value
def test_bad_signature_exception(self, serializer: Serializer, value: Any): bad_signed = serializer.dumps(value)[:-1] with pytest.raises(BadSignature) as exc_info: serializer.loads(bad_signed) payload = cast(bytes, exc_info.value.payload) assert serializer.load_payload(payload) == value
def test_changed_value(self, serializer: Serializer, value: Any, transform): signed = serializer.dumps(value) assert serializer.loads(signed) == value changed = transform(signed) with pytest.raises(BadSignature): serializer.loads(changed)
def test_bad_payload_exception(self, serializer: Serializer, value: Any): original = serializer.dumps(value) payload = original.rsplit(coerce_str(original, "."), 1)[0] # type: ignore bad = serializer.make_signer().sign(payload[:-1]) with pytest.raises(BadPayload) as exc_info: serializer.loads(bad) assert exc_info.value.original_error is not None
def test_file(self, serializer: Serializer, value: Any): f = cast( IO, BytesIO() if isinstance(serializer.dumps(value), bytes) else StringIO()) serializer.dump(value, f) f.seek(0) assert serializer.load(f) == value f.seek(0) assert serializer.load_unsafe(f) == (True, value)
def test_signer_cls(self, serializer_factory, serializer: Serializer, value: Any): class Other(serializer.signer): # type: ignore default_key_derivation = "hmac" other = serializer_factory(signer=Other) assert other.loads(other.dumps(value)) == value assert other.dumps(value) != serializer.dumps(value)
def _get_serializer(secret_key, salt): """Get the appropriate serializer to use; either ``itsdangerous``, if a secret key is specified, or plain ``pickle`` otherwise. """ # Import in function scope to make itsdangerous an optional dependency if secret_key: from itsdangerous.serializer import Serializer return Serializer(secret_key, salt=salt, serializer=pickle) else: return pickle
def _get_serializer(secret_key, salt): """Get the appropriate serializer to use; either ``itsdangerous``, if a secret key is specified, or plain ``pickle`` otherwise. Raises: py:exc:`ImportError` if ``secret_key`` is specified but ``itsdangerous`` is not installed """ if secret_key: from itsdangerous.serializer import Serializer return Serializer(secret_key, salt=salt, serializer=pickle) else: return pickle
def test_iter_unsigners(self, serializer: Serializer, serializer_factory): class Signer256(serializer.signer): # type: ignore default_digest_method = hashlib.sha256 serializer = serializer_factory( secret_key="secret_key", fallback_signers=[ { "digest_method": hashlib.sha256 }, (Signer, { "digest_method": hashlib.sha256 }), Signer256, ], ) unsigners = serializer.iter_unsigners() assert next(unsigners).digest_method == hashlib.sha1 for signer in unsigners: assert signer.digest_method == hashlib.sha256
def test_loads_unsafe(self, serializer: Serializer, value: Any): signed = serializer.dumps(value) assert serializer.loads_unsafe(signed) == (True, value) bad_signed = signed[:-1] assert serializer.loads_unsafe(bad_signed) == (False, value) payload = signed.rsplit(coerce_str(signed, "."), 1)[0] # type: ignore bad_payload = serializer.make_signer().sign(payload[:-1])[:-1] assert serializer.loads_unsafe(bad_payload) == (False, None) class BadUnsign(serializer.signer): # type: ignore def unsign(self, signed_value, *args, **kwargs): try: return super().unsign(signed_value, *args, **kwargs) except BadSignature as e: e.payload = None raise serializer.signer = BadUnsign assert serializer.loads_unsafe(bad_signed) == (False, None)
from fastapi.responses import Response from itsdangerous.serializer import Serializer from .settings import SECRET_KEY, ACCESS_TOKEN_EXPIRE_MINUTES, AUTH_COOKIE_NAME serializer = Serializer(str(SECRET_KEY)) def set_auth(response: Response, user_id: int): val = serializer.dumps(user_id) response.set_cookie( AUTH_COOKIE_NAME, val, secure=False, expires=ACCESS_TOKEN_EXPIRE_MINUTES * 60, httponly=True, samesite="Lax", ) def logout(response: Response): response.delete_cookie(AUTH_COOKIE_NAME)
''' Created on 9 lug 2021 @author: adamou ''' from itsdangerous.serializer import Serializer from itsdangerous.exc import BadSignature, BadData s = Serializer("secret-key") decoded_payload = None try: decoded_payload = s.loads('[1,2,3,4,5]') # 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
def test_signer_kwargs(self, serializer_factory, serializer: Serializer, value: Any): other = serializer_factory(signer_kwargs={"key_derivation": "hmac"}) assert other.loads(other.dumps(value)) == value assert other.dumps("value") != serializer.dumps("value")
''' @Author: yeshan333 @Date: 2020-03-14 17:58:23 @GitHub: https://github.com/yeshan333 @Contact: [email protected] @License: @LastEditTime: 2020-03-14 20:22:33 @Description: ''' from itsdangerous.serializer import Serializer from itsdangerous import JSONWebSignatureSerializer s = Serializer("secret-key") print(s.dumps([1, 2, 3, 4])) # itsdangerous.exc.BadSignature: Signature b'r7R9RhGgDPvvWl3iNzLuIIfELmo' does not match # print(s.loads('[1, 2, 3].r7R9RhGgDPvvWl3iNzLuIIfELmo')) jws = JSONWebSignatureSerializer("secret-key") print(jws.dumps(0, header_fields={"v": 1})) print( jws.loads( "eyJ2IjoxLCJhbGciOiJIUzUxMiJ9.MA.JO6MA9EEyQPvf_IbRuP6zT9Sa2KjKOxub2ssCpgHCj_ZqsOkCxlFvp1QebNuDHhz8UHiO1EbAG80HrQQyJD7CA", return_header=True))
def test_serializer(self, serializer: Serializer, value: Any): assert serializer.loads(serializer.dumps(value)) == value
from itsdangerous.serializer import Serializer s = Serializer("secret-key") serializer_value = s.dumps([1, 2, 3, 4]) print(serializer_value) print(s.loads(serializer_value)) from itsdangerous.url_safe import URLSafeSerializer s1 = URLSafeSerializer("secret-key", salt="activate") s1.dumps(1) s2 = URLSafeSerializer("secret-key", salt="upgrade") s2.dumps(1) print(s1.dumps(1)) print(s2.dumps(1)) print(s1.loads(s1.dumps(1))) print(s2.loads(s2.dumps(1))) s = URLSafeSerializer("secret-key") s.dumps([1, 2, 3, 4]) print(s.dumps([1, 2, 3, 4])) print(s.loads(s.dumps([1, 2, 3, 4])))
raw_str = s.unsign(b'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA') print(raw_str) #输出 b'my string' 详解: 1)Signer类必须接收一个参数,作为秘钥,进行相关的初始化,例如:初始化 派生秘钥,盐值,哈希算法,具体可以查看源代码。 2)签名的时候默认先把 字符串 进行 utf8编码,然后计算签名。所以如果是中文,这里要注意了。 3)unsign 方法用来 验证 签名字符串是否是 合法的。如果验证通过,返回字符串本身(bytes类型)。 2. Serializer 类 Signer类 只能签名字符串,为了可以签名其他类型数据,Serializer 类提供了两个方法dumps/loads,类似json模块。 基本使用例子: from itsdangerous.serializer import Serializer s = Serializer("secret-key") ret = s.dumps([1, 2, 3, 4]) print(ret) # str类型:[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo raw_list = s.loads('[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo') print(raw_list) # list类型: [1, 2, 3, 4] 详解: 1) dumps 先把 列表 序列化成 字符串,然后进行签名。 2) loads 验证 签名,如果通过,返回 反序列数据。 3) 可以通过定义子类的方式,更改 序列化 使用的模块。(默认使用 json模块) 3. 如果想要你的签名 支持有效期, 请参考:https://itsdangerous.palletsprojects.com/en/1.1.x/timed/