CherryPy webapp 的基本身份验证

Basic Auth for CherryPy webapp

我正在尝试创建一个非常基本的 cherrypy webapp,它会在第一个(也是唯一一个)页面加载之前要求用户输入用户名和密码。我在这里使用了 CherryPy 文档中提出的示例:http://cherrypy.readthedocs.org/en/latest/basics.html#authentication

这是我针对 wsgi.py 的具体代码:

import cherrypy
from cherrypy.lib import auth_basic
from myapp import myapp

USERS = {'jon': 'secret'}

def validate_password(username, password):
    if username in USERS and USERS[username] == password:
       return True
    return False

conf = {
    '/': {
       'tools.auth_basic.on': True,
       'tools.auth_basic.realm': 'localhost',
       'tools.auth_basic.checkpassword': validate_password
    }
}

if __name__ == '__main__':

    cherrypy.config.update({
        'server.socket_host': '127.0.0.1',
        'server.socket_port': 8080,
    })

    # Run the application using CherryPy's HTTP Web Server
    cherrypy.quickstart(myapp(), '/', conf)

上面的代码会给我一个浏览器 user/pass 提示,但是当我点击提示的确定时,我收到以下错误:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 667, in respond
    self.hooks.run('before_handler')
  File "/usr/local/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 114, in run
    raise exc
TypeError: validate_password() takes exactly 2 arguments (3 given)

我不确定它认为第三个参数是从哪里来的。有什么想法吗?谢谢!

来自 cherrypy 的文档

   checkpassword: a callable which checks the authentication credentials.
        Its signature is checkpassword(realm, username, password). where
        username and password are the values obtained from the request's
        'authorization' header.  If authentication succeeds, checkpassword
        returns True, else it returns False.

因此,您的 checkpassword 实现必须遵循相同的 api,即:checkpassword(realm, username, password),而您向我们展示的缺少第一个参数 - realm。