簡體   English   中英

哪個 Timed JSONWebSignature Serializer 替代 itsdangerous 更好? pyjwt 或 authlib

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

目前我正在使用itsdangerous生成定時 json Web 簽名作為用戶進行身份驗證和重置密碼等的令牌。這是代碼:

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

而且由於TimedJSONWebSignatureSerializeritsdangerous2.1.0中已被棄用和刪除,我想我可能需要繼續使用其他一些提供 JWT/JWS 接口的庫。

在這里我有兩個候選人,哪個更好:

哪個庫被評為“更好”在很大程度上取決於用例。

如果你想保持簡短,我會推薦 pyjwt。 設置過期時間很容易,而我在 authlib JWS 文檔中找不到適合該選項的標志。 因此,只需按如下方式更改您的代碼:

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

希望我能幫上忙!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM