[Twisted-Python] How to do basic authentication on twisted web

Reza Lotun rlotun at gmail.com
Mon Aug 17 09:05:48 EDT 2009

Hi Chris,

> My annotated example is also up on github - http://gist.github.com/169102
> The original on twisted matrix
> http://twistedmatrix.com/projects/web/documentation/examples/webguard.py

Generally it looks fine - but I should mention these random snippets
of code were given with the assumption that a .tac file is being used.
A .tac file is basically a "runner" script or driver for your twisted
program - it works in conjunction with the twistd command-line utility
and does fun stuff like automatic daemonization and reactor selection.

Anyway, the snippets I gave would integrate into the webguard.py
example like so (imports omitted for clarity):

class GuardedResource(resource.Resource):
    A resource which is protected by guard and requires authentication in order
    to access.
    def getChild(self, path, request):
        return self

    def render(self, request):
        return "Authorized!"

class SimpleRealm(object):
    A realm which gives out L{GuardedResource} instances for authenticated

    def requestAvatar(self, avatarId, mind, *interfaces):
        if resource.IResource in interfaces:
            return resource.IResource, GuardedResource(), lambda: None
        raise NotImplementedError()

def cmp_pass(uname, password, storedpass):
    return crypt.crypt(password, storedpass[:2])

def main():
    # add in the path to your .htpasswd in place of path_to_htpasswd
    checkers = [FilePasswordDB(path_to_htpasswd,
    wrapper = guard.HTTPAuthSessionWrapper(
                    Portal(SimpleRealm(), checkers),
    reactor.listenTCP(8080, server.Site(
                               resource = wrapper))

if __name__ == '__main__':

This should basically run (though I haven't tested this specific example).


Reza Lotun
mobile: +44 (0)7521 310 763
email:  rlotun at gmail.com
work:   reza at tweetdeck.com
twitter: @rlotun

More information about the Twisted-Python mailing list