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"'})
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)
This gives you the basic apache 401 response. Does anyone know how I can implement that with the snippet above?
Thanks
Flask's
abort
comes directly from Werkzeug. It is a callable object, that raises various predefined HTTP exceptions (subclasses ofHTTPException
) on demand. Check out the code here for details.The predefined
Unauthorized
(which is mapped to 401) only defines the code and a message, but not theWWW-Authenticate
header, which as you know is required to trigger the login-popup with browsers. The headers anHTTPException
has are hardcoded as[('Content-Type', 'text/html')]
inHTTPException.get_headers
.So to add the
WWW-Authenticate
header create your ownUnauthorized
subclass, overwrite theget_headers
function and finally update theabort.mapping
dictionary with it.Now all
abort(401)
calls will raise your custom exception.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.
You can then use
abort(401)
to your heart's content.