胖蔡说技术
随便扯扯

Python报错Cannot import name ‘TimedJSONWebSignatureSerializer‘ from ‘itsdangerous‘

使用flask-httpauth实现JWS验证,通过TimedJSONWebSignatureSerializer实现token的序列化,发现报错信息:cannot import name ‘TimedJSONWebSignatureSerializer‘ from ‘itsdangerous‘。检查依赖库发现TimedJSONWebSignatureSerializer不存在。检查itsdangerous版本发布信息发现:

发现itsdangerous库自从2.0以后版本已经不在支持JSONWebSignatureSerializerTimedJSONWebSignatureSerializer功能的实现,建议使用JWS/JWT库替代,如authlib

安装

$pip install authlib

如下是使用JWT方式实现authlib辅助HTTPTokenAuth验证Token的功能,示例代码如下:

from flask import Flask
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from authlib.jose import jwt, JoseError


app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
token_serializer = Serializer(app.config['SECRET_KEY'], expires_in=3600)

auth = HTTPTokenAuth('Bearer')

users = [{"id": 1, "name": 'cai'}, {"id": 2, "name": 'susan'}]


def generate_token(user, operation, **kwargs):
    """生成用于邮箱验证的JWT(json web token)"""
    # 签名算法
    header = {'alg': 'HS256'}
    # 用于签名的密钥
    key = app.config['SECRET_KEY']
    # 待签名的数据负载
    data = {'id': user.id, 'operation': operation}
    data.update(**kwargs)
    return jwt.encode(header=header, payload=data, key=key)


def validate_token(user, token, operation):
    """用于验证用户注册和用户修改密码或邮箱的token, 并完成相应的确认操作"""
    key = app.config['SECRET_KEY']

    try:
        data = jwt.decode(token, key)
        print(data)
    except JoseError:
        return False
    ... # 其他字段确认
    return True

for user in users:
    token =  generate_token(user)
    print('*** token for {}: {}\n'.format(user, token))


@auth.verify_token
def verify_token(token):
    try:
        data = validate_token(token)
    except:  # noqa: E722
        return False
    if 'username' in data:
        return data['username']


@app.route('/')
@auth.login_required
def index():
    return "Hello, %s!" % auth.current_user()


if __name__ == '__main__':
    app.run()
赞(2) 打赏
转载请附上原文出处链接:胖蔡叨叨叨 » Python报错Cannot import name ‘TimedJSONWebSignatureSerializer‘ from ‘itsdangerous‘
分享到: 更多 (0)

请小编喝杯咖啡~

支付宝扫一扫打赏

微信扫一扫打赏