Which Timed JSONWebSignature Serializer replacement for itsdangerous is better? pyjwt or authlib
Asked Answered
T

1

9

Currently I was using itsdangerous to generate timed json web signature as a token for users to auth and resetpassword etc. Here's the code:

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

class SampleCode:
    def generate_confirmation_token(self, expiration=600):
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'confirm': self.id}).decode('utf-8')

    def confirm(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token.encode('utf-8'))
        except:
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        return True

And since TimedJSONWebSignatureSerializer is deprecated and removed in itsdangerous 2.1.0 I think I might need to move on to some other libs that provides a JWT/JWS interface.

And here I've got two candidates, which one is better:

Transceiver answered 28/2, 2022 at 9:18 Comment(2)
@RobinUphoff, I do wish, If it's possible, don't copy my code. github.com/realJustinLee/LiCMS/commit/…Transceiver
With all respect Justin, but when revising the former code and following pyjwts documentation this is the result. I did not see any code of your project before. If you already found the solution, you could have posted it here...Collettecolletti
C
15

Which library is to be rated as "better" depends very much on the use case.

If you want to keep it short and simple, I would recommend pyjwt. Its easy to set the expiration time, whereas i could not find a suited flag for that option in the authlib JWS documentation. So just change your code as follows:

import jwt
import datetime

class SampleCode:
    def generate_confirmation_token(self, expiration=600):
        reset_token = jwt.encode(
            {
                "confirm": self.id,
                "exp": datetime.datetime.now(tz=datetime.timezone.utc)
                       + datetime.timedelta(seconds=expiration)
            },
            current_app.config['SECRET_KEY'],
            algorithm="HS256"
        )
        return reset_token

    def confirm(self, token):
        try:
            data = jwt.decode(
                token,
                current_app.config['SECRET_KEY'],
                leeway=datetime.timedelta(seconds=10),
                algorithms=["HS256"]
            )
        except:
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        return True

Hope I could help!

Collettecolletti answered 2/5, 2022 at 18:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.