密码保护Flask应用程序中的一个网页

acc*_*lke 3 python apache .htaccess basic-authentication flask

我正在运行Flask Web应用程序并使用Apache基本身份验证(使用.htaccess和.htpasswd文件)来对其进行密码保护.我想密码保护应用程序中的一个网页.当我用密码保护网页的html文件时没有任何效果,网页仍然没有密码保护.这可能是因为我的python文件是使用render_template调用html文件的吗?我不知道如何解决这个问题.

dir*_*irn 12

您需要限制对端点的访问.这个片段应该让你开始走正确的道路.

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

有了这个,你可以装饰你想要限制的任何端点@requires_auth.

@app.route('/secret-page')
@requires_auth
def secret_page():
    return render_template('secret_page.html')
Run Code Online (Sandbox Code Playgroud)