密码保护Flask应用程序中的一个网页 [英] Password Protect one webpage in Flask app
问题描述
您需要限制对端点的访问。 这个片段应该让你开始正确的道路。
$从functools进口包装
def check_auth(username,password)$:
$ p $
返回用户名=='admin'和密码=='secret'
$ b $ def authenticate():
发送401响应,启用基本身份验证
返回响应(
'无法验证您的访问级别那个URL.\\\
'
'你必须用适当的凭证登录',401,
{'WWW-Authenticate':'Basic realm =需要登录})
def require_auth(f):
@wraps(f)
def装饰(* args,** kwargs):
auth = request.authorization
如果不是auth或者不是check_auth(auth.username,auth.password):
返回authenticate()
返回f(* args,** kwargs)
返回装饰
有了这个,你可以用 @requires_auth
来装饰你想要限制的任何端点。
@ app.route('/ secret-page')
@requires_auth
def secret_page():
return render_template('secret_page.html')
I am running a Flask web app and using Apache basic authentication(with .htaccess and .htpasswd files) to password protect it. I want to password protect only one webpage in the app. When I password protect the html file for the webpage there is no effect and the webpage is still not password protected. Could this be because it is my python file that is calling the html file using render_template? I'm not sure how to fix this issue.
You need to restrict access to your endpoint. This snippet should get you started down the right path.
from functools import wraps
from flask import request, Response
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'secret'
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
With this, you could decorate any endpoint you want to restrict with @requires_auth
.
@app.route('/secret-page')
@requires_auth
def secret_page():
return render_template('secret_page.html')
这篇关于密码保护Flask应用程序中的一个网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!