在烧瓶中使用HTTP auth时的标准401响应

ing*_*.am 19 python apache2 http-authentication abort flask

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

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

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

abort(401)
Run Code Online (Sandbox Code Playgroud)

这为您提供了基本的apache 401响应.有谁知道我如何使用上面的代码段实现它?

谢谢

ʇsә*_*ɹoɈ 27

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

然后,您可以使用abort(401)您的内心.


Flo*_*ian 13

Flask's abort直接来自Werkzeug.它是一个可调用对象,可根据需要引发各种预定义的HTTP异常(子类HTTPException).有关详细信息,请查看此处的代码.

预定义Unauthorized(映射到401)仅定义代码和消息,但不定义WWW-Authenticate标头,如您所知,需要使用浏览器触发登录弹出窗口.一个标头HTTPException有被硬编码[('Content-Type', 'text/html')]HTTPException.get_headers.

因此,要添加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})
Run Code Online (Sandbox Code Playgroud)

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