一直在学习Tvisted周,读过这本书和大部分码头,但我无法理解单一时刻。来自Twisted文档 http://twistedmatrix.com/documents/10.1.0/core/howto/pb-cred.html 服务器
#!/usr/bin/env python
# Copyright (c) 2009 Twisted Matrix Laboratories.
# See LICENSE for details.
from zope.interface import implements
from twisted.spread import pb
from twisted.cred import checkers, portal
from twisted.internet import reactor
class MyPerspective(pb.Avatar):
def __init__(self, name):
self.name = name
def perspective_foo(self, arg):
print "I am", self.name, "perspective_foo(",arg,") called on", self
class MyRealm:
implements(portal.IRealm)
def requestAvatar(self, avatarId, mind, *interfaces):
if pb.IPerspective not in interfaces:
raise NotImplementedError
return pb.IPerspective, MyPerspective(avatarId), lambda:None
p = portal.Portal(MyRealm())
c = checkers.InMemoryUsernamePasswordDatabaseDontUse(user1="pass1",
user2="pass2")
p.registerChecker(c)
reactor.listenTCP(8800, pb.PBServerFactory(p))
reactor.run()
客户端
#!/usr/bin/env python
# Copyright (c) 2009 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.spread import pb
from twisted.internet import reactor
from twisted.cred import credentials
def main():
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8800, factory)
def1 = factory.login(credentials.UsernamePassword("user1", "pass1"))
def1.addCallback(connected)
reactor.run()
def connected(perspective):
print "got perspective1 ref:", perspective
print "asking it to foo(13)"
perspective.callRemote("foo", 13)
main()
如果用户输入了错误的密码:
Unhandled Error
Traceback (most recent call last):
Failure: twisted.cred.error.UnauthorizedLogin:
我代替例外,告诉用户他没有输入正确的密码?\ bad username
我试图改变:
c = checkers.InMemoryUsernamePasswordDatabaseDontUse(user1="pass1",user2="pass2")
p.registerChecker(c)
on
passwords = {
'admin': 'aaa',
'user1': 'bbb',
'user2': 'ccc'
}
p.registerChecker(PasswordDictChecker(passwords))
class PasswordDictChecker(object):
implements(checkers.ICredentialsChecker)
credentialInterfaces = (credentials.IUsernamePassword,)
def __init__(self, passwords):
"passwords: a dict-like object mapping usernames to passwords"
self.passwords = passwords
def requestAvatarId(self, credentials):
username = credentials.username
if self.passwords.has_key(username):
if credentials.password == self.passwords[username]:
return defer.succeed(username)
else:
return defer.fail(
credError.UnauthorizedLogin("Bad password"))
else:
return defer.fail(
credError.UnauthorizedLogin("No such user"))
但是出现了错误,我认为这是错误的方式。
P.S。我知道如何在没有Perspective Broker的情况下进行身份验证...
答案 0 :(得分:0)
如果要实施重试,请在客户端完全执行。您应该不更改服务器以报告“密码错误”或“没有此类用户”等消息,因为这些信息会泄露给攻击者。
要让客户端重试,请在登录时添加一个errback,提示输入新密码(可能是新用户)并再次调用login。