flaskauthlibpyjwtitsdangerous

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


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:


Solution

  • 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!