Standard 401 response when using HTTP auth in flask

前端 未结 2 1770
广开言路
广开言路 2021-02-05 05:40

In flask, I\'m using the following snippet to enable HTTP auth:

def authenticate():
    return Response(\'\', 401         


        
2条回答
  •  余生分开走
    2021-02-05 05:48

    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 = ''
        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.

提交回复
热议问题