我用flask做了很多开发工作,但还没有深入研究使用用户身份验证来保护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中最安全的多用户身份验证方法
发布于 2019-04-24 06:50:57
您需要一个处理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请求。希望这能有所帮助!
https://stackoverflow.com/questions/55820279
复制相似问题