Search code examples
pythonauthenticationflaskxml-rpchttp-authentication

Use Flask XML-RPC with HTTPAuth?


I am using the Flask XML-RPC extension and everything is working well. Now I want to protect the XML-RPC endpoint with a basic HTTP authentication using Flask HTTPAuth extension.

This extension is usually used with routes, but the XML-RPC endpoint is not defined as a route:

handler = XMLRPCHandler('xmlrpc')
handler.connect(app, '/xml-rpc')

def hello_word():
    return "Hello"

handler.register_function(hello_world)

How can I use HTTP authentication with Flask-XML-RPC so that any caller of /xml-rpc has to authenticate?


Solution

  • You'll have to subclass the XMLRPCHandler() class; each call through /xml-rpc is handled by the XMLRPCHandler.handle_request() method, you can decorate that to handle authentication:

    class HTTPAuthXMLRPCHandler(XMLRPCHandler):
        @auth.login_required
        def handle_request(self):
            return XMLRPCHandler.handle_request(self)
    
    handler = HTTPAuthXMLRPCHandler('xmlrpc')
    handler.connect(app, '/xml-rpc')