【问题标题】:Standard 401 response when using HTTP auth in flask在烧瓶中使用 HTTP 身份验证时的标准 401 响应
【发布时间】:2011-10-24 14:32:07
【问题描述】:

在烧瓶中,我使用以下snippet 来启用 HTTP 身份验证:

def authenticate():
    return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'})

现在,根据我过去使用 Flask 的经验,如果有人的凭据不正确,我想让他们知道我可以打电话:

abort(401)

这为您提供了基本的 apache 401 响应。有谁知道我如何使用上面的 sn-p 来实现它?

谢谢

【问题讨论】:

  • 如果您有不同的401原因,abort(401, '&lt;Why access is denied string goes here...&gt;')也可以。

标签: python apache2 flask http-authentication abort


【解决方案1】:

在 Flask 中自定义错误响应非常简单。创建一个函数,其唯一参数是HTTP错误状态码,让它返回一个flask.Response实例,并用@app.errorhandler装饰它。

@app.errorhandler(401)
def custom_401(error):
    return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'})

然后您可以尽情使用abort(401)

【讨论】:

  • 这需要是“WWW-Authenticate”(带有破折号!)才能在浏览器中正常工作。
  • 确实如此。固定。
【解决方案2】:

Flask 的abort 直接来自 Werkzeug。它是一个可调用对象,可按需引发各种预定义的 HTTP 异常(HTTPException 的子类)。详情请查看代码here

预定义的Unauthorized(映射到401)只定义了代码和消息,但没有定义WWW-Authenticate标头,正如您所知,这是触发浏览器登录弹出窗口所必需的。 HTTPException 的标头在HTTPException.get_headers 中硬编码为[('Content-Type', 'text/html')]

所以要添加WWW-Authenticate 标头,创建自己的Unauthorized 子类,覆盖get_headers 函数,最后用它更新abort.mapping 字典。

from flask import abort
from werkzeug.exceptions import Unauthorized

class MyUnauthorized(Unauthorized):
    description = '<Why access is denied string goes here...>'
    def get_headers(self, environ):
        """Get a list of headers."""
        return [
            ('Content-Type', 'text/html'),
            ('WWW-Authenticate', 'Basic realm="Login required"'),
        ]

abort.mapping.update({401: MyUnauthorized})

现在所有abort(401) 调用都会引发您的自定义异常。

【讨论】:

  • 谢谢!很好的解释。我会试试这个:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 2021-09-06
  • 2020-03-13
相关资源
最近更新 更多