我试图使用Twisted的HTTP基本身份验证来控制对某些受保护资源的访问。
根据一些文章,有必要使用三个重要的概念:领域,门户和化身。现在我想知道王国和化身是否是一对一的通信。
让我们看一个例子
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()当然,我知道SimpleRealm用于返回相应的资源,例如上面的示例中的GuardedResource。然而,当有大量的资源需要保护时,我不知道该怎么做。例如,我有GuardedResource1、GuardedResource2和GuardedResource3,它们在初始化时可能需要相同或不同数量的参数;如果需要,是否需要分别实现SimpleRealm1、SimpleRealm2和SimpleRealm3?
发布于 2015-12-25 01:58:50
有人在Twisted邮件列表中问了同样的问题,其中包含了非常相似的代码示例-- http://twistedmatrix.com/pipermail/twisted-python/2015-December/030042.html --所以我将参考我在那里的回答:http://twistedmatrix.com/pipermail/twisted-python/2015-December/030068.html
与其认为资源总是存在的,而且只需要对其进行锁定,不如考虑更灵活的模型( cred实际上实现的模型),其中一个Avatar对象(在本例中是:从SimpleRealm返回的顶级SimpleRealm)是“用户可以访问的所有东西”的顶层。换句话说,“GuardedResource”应该有一个“getChild”方法,该方法确定他们所代表的用户(实际上,至少应该向GuardedResource提供avatarId )访问其他资源,如果有,则返回这些资源,如果没有,则返回适当的错误。 即使是未登录用户可用的资源(请参见twisted.cred.credentials.Anonymous)也只是另一个化身,它提供给未经身份验证的用户。 因此,如果有https://myapp.example.com/a/b/secure/c/d https://myapp.example.com/a/b/secure/c/d,https://myapp.example.com/a/b/secure https://myapp.example.com/a/b/secure将是受保护的资源,然后是SecureResource.getChild("c",.)将返回"c",如果登录用户能够访问它,则返回"d“。
希望这个答案对清单上的你有用:-)。
https://stackoverflow.com/questions/34258556
复制相似问题