[Twisted-Python] What are the relationships between twisted.cred.portal.IRealm, Portal and avatar

Wang Yan snailcoder at 163.com
Sun Dec 13 08:50:50 MST 2015


I'm trying to use Twisted's HTTP basic authentication to control access to some protected resources.


According to some articles, it is necessary to use three important concepts: Realm, Portal and avatar. Now I'm wondering if the Realm and avatar is one to one correspondence.


Let's look at an example(http://www.red-bean.com/doc/python-twisted-web/examples/webguard.py):


import sys

from zope.interface import implements

from twisted.python import log
from twisted.internet import reactor
from twisted.web import server, resource, guard
from twisted.cred.portal import IRealm, Portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse


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
    users.
    """
    implements(IRealm)

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



def main():
    log.startLogging(sys.stdout)
    checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')]
    wrapper = guard.HTTPAuthSessionWrapper(
        Portal(SimpleRealm(), checkers),
        [guard.DigestCredentialFactory('md5', 'example.com')])
    reactor.listenTCP(8889, server.Site(
          resource = wrapper))
    reactor.run()

if __name__ == '__main__':
    main()


Of course I know the SimpleRealm is used to return the corresponding resource, e.g. GuardedResource in above example. However, I don't know what to do when there lots of resources to be guarded. For example, I have GuardedResource1, GuardedResource2 and GuardedResource3, maybe they need the same or different number of parameters when they are initialized; If so, is it necessary to implement SimpleRealm1, SimpleRealm2 and SimpleRealm3, respectively? 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-python/attachments/20151213/66fa0e79/attachment.html>


More information about the Twisted-Python mailing list