2015-12-14 35 views
0

我試圖使用Twisted的HTTP基本身份驗證來控制對某些受保護資源的訪問。twisted.cred.portal.IRealm,門戶和頭像之間的關係是什麼

據一些文章,有必要使用三個重要概念:領域,門戶網站和頭像。現在我想知道Realm和頭像是否是一一對應的。

讓我們來看一個例子

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?

回答

0

有人問扭曲的郵件列表上同樣的問題,具有非常相似的代碼示例 - http://twistedmatrix.com/pipermail/twisted-python/2015-December/030042.html - 所以我將把你我的回答有:http://twistedmatrix.com/pipermail/twisted-python/2015-December/030068.html

,而不是資源的思想一如既往現有隻需要鎖定或不鎖定,考慮一個單一的Avatar對象(在這種情況下:從SimpleRealm返回的頂級IResource)的最靈活的模型(Cred實際實現的模型)是「用戶有權訪問「。換句話說,「GuardedResource」應該有一個「getChild」方法,該方法使判定如果它們表示用戶(實際上,至少avatarId應供給至GuardedResource。INIT)具有訪問其他資源,並且如果返回它們所以,如果不是,則適當的錯誤。

即使是提供給一個不登錄的用戶資源(見twisted.cred.credentials.Anonymous)只是另一種化身,一個擔任了未經認證的人。

所以,如果你有https://myapp.example.com/a/b/secure/c/dhttps://myapp.example.com/a/b/secure/c/dhttps://myapp.example.com/a/b/securehttps://myapp.example.com/a/b/secure將是謹慎的資源,然後SecureResource.getChild(「C」,...)將返回「C」,而後者將在重返「d」,如果登錄用戶可以訪問它。

希望這個答案在你的名單上工作:-)。

相關問題