使用flask-httpauth
实现JWS
验证,通过TimedJSONWebSignatureSerializer
实现token
的序列化,发现报错信息:cannot import name ‘TimedJSONWebSignatureSerializer‘ from ‘itsdangerous‘
。检查依赖库发现TimedJSONWebSignatureSerializer
不存在。检查itsdangerous
版本发布信息发现:
发现itsdangerous
库自从2.0
以后版本已经不在支持JSONWebSignatureSerializer
, TimedJSONWebSignatureSerializer
功能的实现,建议使用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()