【问题标题】:Simple authentication in Flask not working under ApacheFlask 中的简单身份验证在 Apache 下不起作用
【发布时间】:2015-10-12 04:59:01
【问题描述】:

我正在用 Flask 构建一个网站,现在我想用一个非常简单的身份验证机制来保护一个管理员视图。为此,我编写了以下包装代码:

def check_auth(username, password):
    current_app.logger.error('Log from check_auth')
    return username == 'myusername' and password == 'mypassword'

def authenticate():
    current_app.logger.error('Log from authenticate function')
    return Response('Bad luck my friend.', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        current_app.logger.error('Log from requires_auth function')
        auth = request.authorization
        current_app.logger.error(auth)  # <= HERE I LOG auth
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@requires_auth
def some_view():
    return 'some stuff'

这在使用 Flask 开发服务器时可以正常工作。我刚刚在 Apache/mod_wsgi 上部署了它,但不幸的是现在它不起作用;填写我的登录详细信息后,它只是重新加载登录屏幕(提示密码错误)。

我在那里输入了一些日志,现在它会记录以下内容:

Log from requires_auth function
None
Log from authenticate function

如您所见,auth(应包含填写的用户名和密码)仍然为 None。奇怪的是,这三个日志在登录屏幕一显示就已经显示了。这意味着该函数不再等待用户填写他的用户名和密码,而是继续执行。

有人知道我在这里做错了什么吗?为什么它可以与 Flask 开发服务器一起使用,但它不能与 Apache/mod_wsgi 一起使用?欢迎所有提示!

【问题讨论】:

    标签: python apache authentication flask


    【解决方案1】:

    我认为这会有所帮助:

    如果您在 mod_wsgi 中使用基本身份验证,则必须启用身份验证转发,否则 apache 会使用所需的标头并且不会将其发送到您的应用程序:WSGIPassAuthorization。

    http://flask.pocoo.org/snippets/8/

    【讨论】:

    • 非常好。我是 Apache 服务器管理的新手,所以请多多包涵。我在文件/etc/apache2/apache2.conf 中搜索了WSGIPassAuthorization,但它目前不在文件中。我只需要将它添加到底部的文件并重新启动 Apache,还是需要在其他地方设置它?
    • 这取决于您的配置,但我认为是的,您可以在底部添加此指令:stackoverflow.com/questions/9780966/…
    • 最后我把它放在了我在/etc/apache2/sites-available/mysite.com.conf 中的网站的 apache 配置文件中。它现在工作得很好。谢谢一百万!
    猜你喜欢
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2017-01-16
    • 2016-02-23
    相关资源
    最近更新 更多