gpt4 book ai didi

python - 如何让 Flask_Security 中的 auth_token_required 工作?

转载 作者:行者123 更新时间:2023-11-28 22:45:20 25 4
gpt4 key购买 nike

我正在尝试为使用 Flask 的应用程序构建一个基于 token 的后端 (API),我正在尝试在其中使用 Flask_Security .因为我使用的是 Peewee ORM ,我关注了this guide构建基本设置,我现在必须构建应该让用户登录的 View ,然后构建一个实际提供一些有用数据的 View 。

所以我返回 token 的登录 View 如下所示:

@app.route('/api/login', methods=['POST'])
def api_login():
requestJson = request.get_json(force=True)
user = User.select().where(User.username == requestJson['username']).where(User.password == requestJson['password']).first()
if user:
return jsonify({'token': user.get_auth_token()})
else:
return jsonify({'error': 'LoginError'})

这很好用;我得到一个 token 作为回应。我现在想使用 auth_token_required 保护另一个 View ,我想使用 token 作为 header 。所以我尝试如下:

@app.route('/api/really-important-info')
@auth_token_required('SECURITY_TOKEN_AUTHENTICATION_HEADER')
def api_important_info():
return jsonify({'info': 'really important'})

但是启动 Flask 会导致 AttributeError: 'str' object has no attribute '__module__'The documentation对它的使用也不是很有帮助。

有人知道我怎样才能让它工作吗?欢迎任何提示!

最佳答案

错误是因为装饰器不期望任何参数(除了它正在装饰的函数)。

@auth_token_required
def api_important_info():
pass

配置值 SECURITY_TOKEN_AUTHENTICATION_KEYSECURITY_TOKEN_AUTHENTICATION_HEADER 分别表示传入请求的查询参数或 header 中的位置。

Flask-安全 automatically sends this token当向登录路由发出 JSON 请求时,发送给客户端以备将来使用。


您可能会对 Flask-Security 提供的多种身份验证方法感到困惑。授权 token 对于没有浏览器管理的 session cookie 的 api 很有用。 “正常”基于 session 的身份验证由 login_required 处理.

关于python - 如何让 Flask_Security 中的 auth_token_required 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28727954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com