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

Reza Lotun rlotun at gmail.com
Mon Aug 17 05:45:35 EDT 2009

Hi Chris,

> I'm using twisted-web on an openwrt computer, using busybox, and after
> looking through the docs, I'm a little unclear about how to implement
> something like apache's htpasswd style authentication.
> Using apache, I'd do something like:
> htpasswd -c passwrods admin topSecretPassword
> What's the simplest way to add a simple check for a username and
> password like this using twisted web?
> Where possible, I'd like to keep all of this inside twisted rather
> than rely on installing other binaries, that might not work within the
> confined of a small openwrt install.

The short answer is that you need to use twisted.cred. It's an
abstraction that allows you to implement authentication without
directly exposing the hashing method or password database details.
Take a look at this example:

It demonstrates an in memory database, which should generally be used
for testing/debugging only - but you might not care about that an be
happy to have an in memory database. If you want to use an .htaccess
apache style password db, you'll have to make a slight modification:

from twisted.web import guard, server
from twisted.cred.portal import Portal
from twisted.cred.checkers import FilePasswordDB

import crypt

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

checkers = [FilePasswordDB(path_to_htpasswd,
 wrapper = guard.HTTPAuthSessionWrapper(
                    Portal(SimpleRealm(), checkers),
 return internet.TCPServer(8080, server.Site(resource=wrapper))

I'll probably contribute the Htaccess style checker to twisted at some
point, as I've found it useful in the past and others may too.


Reza Lotun
+44 (0)7521 310 763
rlotun at gmail.com

More information about the Twisted-Python mailing list