I am using Python 3.9 and itsdangerous 2.1.2. I was testing things in the terminal and it does not appear to be working. This is my first experience with itsdangerous so maybe I don't understand it.
I want to get a token that can be emailed for when the user clicks on [forgot password].
My code in terminal:
>>> from itsdangerous import URLSafeTimedSerializer as Serializer
>>> s = Serializer('secret', 300)
>>> token = s.dumps({'user_id': 5}).decode('utf-8')
From above I get an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\...\flask_env\lib\site-packages\itsdangerous\serializer.py", line 208, in dumps
rv = self.make_signer(salt).sign(payload)
File "C:\...\flask_env\lib\site-packages\itsdangerous\timed.py", line 55, in sign
return value + sep + self.get_signature(value)
File "C:\...\flask_env\lib\site-packages\itsdangerous\signer.py", line 209, in get_signature
key = self.derive_key()
File "C:\...\flask_env\lib\site-packages\itsdangerous\signer.py", line 195, in derive_key
bytes, self.digest_method(self.salt + b"signer" + secret_key).digest()
TypeError: unsupported operand type(s) for +: 'int' and 'bytes'
After seeing this answer I changed to the below.
>>> from itsdangerous import URLSafeTimedSerializer as Serializer
>>> s = Serializer('secret')
>>> token = s.dumps({'user_id': 5})
>>> s.loads(token)
{'user_id': 5}
>>> token
'eyJ1c2VyX2lkIjo1fQ.ZEv06A.rc99R7V53CJ1XDM0sk6VJjMFdjQ'
Part of the concept of the integer in s = Serializer('secret', 300)
is to limit the time for the token to work. If I change to the 2nd option will the Serializer
go to a default time out? How could I make it work better?
Is there any concern with having this be the code of a token for a flask app? If it does seem wrong how should I do it?
def get_reset_token(self):
s = Serializer(app.config['SECRET_KEY'])
return s.dumps({'user_id': self.id})
According to docs, 2nd argument to URLSafeTimedSerializer
is salt
which has default value b'itsdangerous'
and if given it should be str
or bytes
instance, 300
is literal for integer and therefore does not met imposed requirments.