在Flask中使用HTTP身份验证时的标准401响应 [英] Standard 401 response when using HTTP auth in flask
问题描述
在烧瓶中,我使用以下代码段启用HTTP身份验证:
In flask, I'm using the following snippet to enable HTTP auth:
def authenticate():
return Response('<Why access is denied string goes here...>', 401, {'WWW-Authenticate':'Basic realm="Login Required"'})
现在,根据我过去在Flask上的经验,如果某人的凭据不正确,我想让他们知道我可以打电话:
Now, in my past experience with Flask, if someone's credentials are incorrect and I want to let them know I can just call:
abort(401)
这为您提供了基本的401响应.有谁知道我如何使用上面的代码片段实现这一目标?
This gives you the basic apache 401 response. Does anyone know how I can implement that with the snippet above?
谢谢
推荐答案
在Flask中,自定义错误响应非常容易.创建一个仅将参数作为HTTP错误状态代码的函数,使其返回flask.Response实例,并使用 @ app.errorhandler .
Custom error responses are really quite easy in Flask. Create a function whose only argument is the HTTP error status code, make it return a flask.Response instance, and decorate it with @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)
来表达自己的内心.
You can then use abort(401)
to your heart's content.
这篇关于在Flask中使用HTTP身份验证时的标准401响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!