Flask基本身份验证不接受用户名和密码。

4

我在服务器上的Flask应用程序中使用BasicAuth。 每当我尝试输入用户名和密码时,该应用程序只会提示我重新输入信息,并且不会对我进行身份验证。 我不确定如何解决这个问题。 我的应用程序中的代码如下:

app.config['BASIC_AUTH_USERNAME'] = 'user'
app.config['BASIC_AUTH_PASSWORD'] = 'password'

basic_auth = BasicAuth(app)
@app.route("/secret")
@basic_auth.required
def secret_view():
    return submit.html
2个回答

3
我在这个 AWS 论坛上找到了答案。问题出在 Elastic Beanstalk 的配置上:必须配置 Apache 以传递认证标头(即来自您的用户的明文用户名和密码)到 Python 应用程序(因此,无论您使用什么解决方案来解析认证凭据,在我的情况下是flask_httpauth),通过 mod_wsgi

为此,在保存在您的.ebextensions文件夹中的.config文件中设置一个容器命令。我使用了以下命令:

.ebextensions/auth.config

container_commands:
  01_wsgi_pass_headers:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

当然,毋庸置疑,由于这些凭证将以明文形式传递,您必须将应用程序设置为仅由HTTPS连接访问!


1
我在标准的Linux / Apache服务器设置上遇到了同样的问题。在这种情况下,解决的另一个选项是将“WSGIPassAuthorization On”添加到Apache主机定义的<Directory ...>部分。 - Ryan D.W.

0

这个简单的例子对我来说很有效:

app.py

from flask import Flask, render_template
from flask.ext.basicauth import BasicAuth

app = Flask(__name__)

app.config['BASIC_AUTH_USERNAME'] = 'user'
app.config['BASIC_AUTH_PASSWORD'] = 'password'

basic_auth = BasicAuth(app)
@app.route("/secret")
@basic_auth.required
def secret_view():
    return render_template('secret_page.html')

if __name__ == '__main__':
    app.run(debug=True)

templates/secret_page.html

秘密页面!

示例请求:

curl -I http://localhost:5000/secret

HTTP/1.0 401 UNAUTHORIZED
WWW-Authenticate: Basic realm=""
Content-Type: text/html; charset=utf-8
Content-Length: 0
Server: Werkzeug/0.10.4 Python/2.7.8
Date: Wed, 15 Apr 2015 04:42:42 GMT

curl -I -u user:password http://localhost:5000/secret
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 12
Server: Werkzeug/0.10.4 Python/2.7.8
Date: Wed, 15 Apr 2015 04:42:54 GMT

curl -u user:password http://localhost:5000/secret
Secret page!

由于某种原因,当我在我的电脑上运行它时,它可以工作,但是当我在服务器上运行它时,用户名和密码无法通过验证,它继续要求凭据。 - accelke
好的,那么你的代码很可能没问题,问题可能是你的 Web 服务器配置出了问题。你应该更新你的问题,提供关于你的 Web 服务器的详细信息,或者提一个新问题,专注于 Web 服务器无法识别 HTTP 基本认证。 - Matt Healy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接