CherryPy Custom Tool for user authentication

戏子无情 提交于 2019-12-01 19:38:20

I was using the wrong hook. Changing:

cherrypy.tools.authenticate = cherrypy.Tool('on_start_resource', authenticate)

To:

cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)

Fixed the problem. Apparently my authenticate method was getting called before sessions had been turned on, so it couldn't access cherrypy.session. I didn't need any session-turn-on stuff in my controllers; all that was necessary was the following in my server-start script:

def authenticate():
    ...
cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)
cherrypy.tree.mount(Root(), "/", config={
    "/": {
        'tools.sessions.on':True,
        'tools.sessions.storage_type':'file',
        'tools.sessions.storage_path':r'%s\sessions' % curDir,
        'tools.sessions.timeout':60
    }, ...
})

Then, in my controller on a restricted method:

@cherrypy.expose
@cherrypy.tools.authenticate()
def home(self, **kwargs):
    ...

Most likely sessions aren't enabled. There's an example config file on the session wiki page, or have a look at tutorial #7.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!