Standard 401 response when using HTTP auth in flask

ingh.am picture ingh.am · Oct 24, 2011 · Viewed 27.1k times · Source

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

Answer

ʇsәɹoɈ picture ʇsәɹoɈ · Nov 29, 2011

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"'})

You can then use abort(401) to your heart's content.