Standard 401 response when using HTTP auth in flask

扶醉桌前 提交于 2020-02-17 22:29:47

问题


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


回答1:


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.




回答2:


Flask's abort comes directly from Werkzeug. It is a callable object, that raises various predefined HTTP exceptions (subclasses of HTTPException) 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 the WWW-Authenticate header, which as you know is required to trigger the login-popup with browsers. The headers an HTTPException has are hardcoded as [('Content-Type', 'text/html')] in HTTPException.get_headers.

So to add the WWW-Authenticate header create your own Unauthorized subclass, overwrite the get_headers function and finally update the abort.mapping dictionary with it.

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

Now all abort(401) calls will raise your custom exception.



来源:https://stackoverflow.com/questions/7877230/standard-401-response-when-using-http-auth-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!