Search code examples
pythonflasktwistedwerkzeug

HTTP Basic Auth on Twisted-Klein server


I am using Twisted-Klein as a server. Here is a simple example:

from klein import Klein


app = Klein()


@app.route('/health', methods=['GET'])
def health_check(request):
    return ''


@app.route('/query/<path:expression>', methods=['GET'])
def query(request, expression):
    return 'Expression: {0}'.format(expression)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

How can I add HTTP Basic Auth to query API endpoint? With Flask, this is simple: http://flask.pocoo.org/snippets/8/

But I fail to find any examples of how to do this on Twisted-Klein server.


Solution

  • Twisted itself has support for HTTP basic (and digest) authentication, factored as a resource wrapper that can be applied to any other resource.

    Your klein example doesn't demonstrate it, but klein can (must, really) create a resource from your app in order to use Twisted's web server.

    You can combine them something like:

    import attr
    from zope.interface import implementer
    from twisted.cred.portal import IRealm
    from twisted.internet.defer import succeed
    from twisted.cred.portal import Portal
    from twisted.web.resource import IResource
    from twisted.web.guard import HTTPAuthSessionWrapper, BasicCredentialFactory
    from klein import Klein
    
    app = Klein()
    # ... define your klein app
    
    @implementer(IRealm)
    @attr.s
    class TrivialRealm(object):
        resource = attr.ib()
    
        def requestAvatar(self, avatarId, mind, *interfaces):
            # You could have some more complicated logic here, but ...
            return succeed((IResource, self.resource, lambda: None))
    
    def resource():
        realm = TrivialRealm(resource=app.resource())
        portal = Portal(realm, [<some credentials checkers>])
        credentialFactory = BasicCredentialFactory(b"http auth realm")
        return HTTPAuthSessionWrapper(portal, [credentialFactory])
    

    You can run this according to the klein docs for using twistd web.