cherrypy会话认证不工作?
我可能忽略了一些简单的东西,但我就是让Cherrypy的SessionAuth无法正常工作。
在调试模式下,如果cherrypy.session里没有用户名,SessionAuth会在日志文件中记录以下内容:
[20/Feb/2013:00:58:39] TOOLS.SESSAUTH No username, routing to login_screen with from_page 'http://localhost:8080/'
问题是它没有跳转到登录页面。它只是返回true给调用者,然后调用者继续执行。它还把cherrypy.serving.response.body设置成一段HTML代码,这段代码应该显示登录页面。但是我的调用函数对response.body一无所知。
我到底哪里做错了呢?
以下是root.py中的相关代码:
class MySessionAuth(cptools.SessionAuth):
def check_username_and_password(self, username, password):
users = dict(foo="bar")
if username in users and password == users[username]:
return False
def on_check(self, username):
cherrypy.session['username'] = username
def session_auth(**kwargs):
sa = MySessionAuth()
for k, v in kwargs.items():
setattr(sa, k, v)
return sa.run()
cherrypy.tools.protect = cherrypy._cptools.Tool('before_handler', session_auth)
class Root:
@cherrypy.expose()
@cherrypy.tools.protect(debug=True)
def index(self):
tmpl = loader.load('index.html')
return tmpl.generate(flash = '',).render('html', doctype='html')
1 个回答
2
如果你想给整个应用程序加上密码保护,而不仅仅是某些特定的资源,你可以创建一个自定义的函数来检查用户名和密码,然后在你的应用程序配置中把这个检查函数指向你创建的那个。
你需要添加的配置行大概是这样的:
'tools.session_auth.check_username_and_password':check_username_and_password
然后只需要使用你上面定义的自定义检查函数,它就应该能正常工作。
下面是一个完整的例子,可以保护应用程序中的所有资源:
import cherrypy
from datetime import datetime
user_dict={'peter':'password','joe':'pass1234','tom':'!Sm,23&$fiuD'}
def check_user(username,password):
if user_dict.has_key(username):
if user_dict[username] == password:
return
else:
return 'incorrect password for user'
return 'user does not exist'
class Root:
@cherrypy.expose
def index(self):
cherrypy.session.regenerate()
cherrypy.session['access_datetime'] = datetime.now()
return """Hello protected resource! <br \>
datetime of access was %s
<br /><a href="./logout">Logout</a>"""%cherrypy.session['access_datetime']
@cherrypy.expose
def logout(self):
username = cherrypy.session['username']
cherrypy.session.clear()
return """%s you have been logged out
of the system at datetime %s"""%(username,datetime.now())
_cp_config={'/':{'tools.sessions.on':True,
'tools.sessions.storage_type':'file',
'tools.sessions.storage_path':'./',
'tools.sessions.timeout':60,
'tools.session_auth.on':True,
'tools.session_auth.check_username_and_password':check_user,
}
}
cherrypy.config.update({'server.socket_host':'0.0.0.0',
'server.socket_port':8090})
cherrypy.quickstart(Root(),'/',config=_cp_config)