【问题标题】:Password Protect one webpage in Flask app密码保护 Flask 应用程序中的一个网页
【发布时间】:2015-06-25 20:10:15
【问题描述】:

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

【问题讨论】:

  • “密码保护html文件”是什么意思?
  • 我的意思是我添加了 .htaccess 和 .htpasswd 文件,并在 .htaccess 文件中指定了 html 文件。访问文件时,这些文件应要求输入用户名和密码。
  • 只有在您直接通过 Apache 提供 HTML 文件时才有效。您需要在 Flask 中限制对端点的访问。
  • 我明白了。我该怎么做?

标签: python apache .htaccess flask basic-authentication


【解决方案1】:

您需要限制对端点的访问。 This snippet 应该会让你走上正确的道路。

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

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

@app.route('/secret-page')
@requires_auth
def secret_page():
    return render_template('secret_page.html')

【讨论】:

  • 其实我之前也用过类似的方法。我使用这种方法遇到的问题是,当我输入用户名和密码时,它只会再次提示输入它们并且它永远不会验证。
  • 来自 sn-p:如果您使用带有 mod_wsgi 的基本身份验证,则必须启用身份验证转发,否则 apache 会使用所需的标头并且不会将其发送到您的应用程序:WSGIPassAuthorization
  • 是的,我确实在我的 /etc/apache2/sites-available/app.com.conf 文件中添加了“WSGIPassAuthorization On”,但它没有任何区别。我必须放入其他文件吗?
  • 有没有办法添加两个可能的用户名密码组合?我希望管理员能够访问其他人无法看到的某些页面,但我希望他们能够使用他们的密码访问其他人可以看到的页面。在生产中,我将使用适当的方法使用完整的用户身份验证,但这是用于初稿测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
相关资源
最近更新 更多