如何在 Flask_Security 中获得 auth_token_required 工作?

kra*_*r65 3 python token flask peewee flask-security

我正在尝试为使用 Flask 的应用程序构建基于令牌的后端(API),其中我正在尝试使用Flask_Security。由于我使用的是Peewee ORM,我已经按照本指南构建了基本设置,现在我必须构建应该登录用户的视图,然后构建一个实际提供一些有用数据的视图。

所以我返回令牌的登录视图如下所示:

@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'})
Run Code Online (Sandbox Code Playgroud)

这很好用;我得到一个令牌作为回应。我现在想保护另一个视图auth_token_required,我想使用令牌作为标题。所以我尝试如下:

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

但是启动 Flask 会导致AttributeError: 'str' object has no attribute '__module__'. 该文档对其使用也不是很有帮助。

有谁知道我怎样才能让它发挥作用?欢迎任何提示!

dav*_*ism 5

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

@auth_token_required
def api_important_info():
    pass
Run Code Online (Sandbox Code Playgroud)

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

当对登录路由发出 JSON 请求时,Flask-Security 会自动将此令牌发送到客户端以备将来使用。


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