首页 > 解决方案 > 使用烧瓶用户登录/身份验证保护页面

问题描述

我已经用烧瓶做了很多开发,但还没有深入研究使用用户身份验证来保护 Web 应用程序。为了这个例子,假设我有基本的设置

from flask import Flask

app = Flask(__name__)

# Can't be accessed if not logged in
@app.route('/secure')
def secure():
    # pseudo code
    if user != authenticated:
        return redirect('login')
    else:
        return render_template('secure.html')

@app.route('/login')
def login():
    return render_template('login.html')

# Called from the login page form
@app.route('/authenticate')
def authenticate():
    # do some code to authenticate, pseudo
    if username in DB and password == password-hash:
        user = authenticated
        return redirect('/')

if __name__ == '__main__':
    app.run()

我能够使用 mongodb 并添加/删除/查询数据。我的问题是我不知道如何将两者联系在一起。用户创建一个帐户,将数据添加到数据库,用户登录,对数据库查询的输入,如果匹配,他们就可以访问该站点。

我遇到的问题是如何让我的 Flask 应用程序知道在用户提供正确的凭据以记住/知道他们是谁并允许他们访问受限页面之后。我想在他们注销之前如何跟踪身份验证状态。

注意:想知道 Flask 中最安全的多用户认证方法

标签: pythonauthenticationflask

解决方案


您需要一个处理 http 方法的 API。Flask-restful 和 Flask-httpauth 你可以编写如下代码:

@marshal_with(piece_fields)
    @auth.login_required
    def post(self):
        args = self.reqparse.parse_args()
        piece = models.Piece.create(**args)
        return piece, 201,
        {'Location': url_for('resources.pieces.Piece', id=Piece.id)}

@auth.login_required 是基本或令牌 http 身份验证(在名为 auth.py 的单独文件中定义),其中包含您的 http 方法。他们将要求使用用户名和密码或令牌发送 http 请求。希望这可以帮助!


推荐阅读