标题中的Cherrypy基本授权 -

时间:2018-04-01 12:32:13

标签: authentication authorization cherrypy

我已经审核了http://cherrypy.readthedocs.io/en/latest/basics.html#authentication上的文档,以了解如何将我的API调用发送到Cherrypy并验证我将在HTTP请求标头中提供的API密钥。我的客户端计划。 标题将遵循基本授权,标题具有以下示例键和值 示例:授权:基本YWxhZGRpbjpvcGVuc2VzYW1l

然后我希望我写的Cherrypy函数只有在完成一些授权后才能运行。 从客户端,我将调用我的函数: HTTPS:/// myfunction的参数1 =值安培; param2的=值安培;参数3 =值 如上所示设置基本授权标题

并且在Cherrypy中我会将函数编码为:

 @cherrypy.expose
    def myfunction(self, param1=1,param2=cat,param3=dog):
            # do my work in the function 
        return 

注意:该功能不会让用户输入任何凭据。该调用将以编程方式预先填充基本授权标头。

您能否以这种方式设置Cherrypy代码示例,以明确告诉我如何实现这一目标。假设有一个使用Cherrypy的初学者(例如,只做了前5个左右的教程(http://docs.cherrypy.org/en/latest/tutorials.html#tutorials)。 非常感谢。

1 个答案:

答案 0 :(得分:1)

import cherrypy

def check_auth():
  needs_auth = cherrypy.request.config.get('auth.require', False)

  if needs_auth and not cherrypy.request.headers.get('X-HTTP-APIKEY', None) =="1234":
     raise cherrypy.HTTPError(401)



cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth, priority=50)


def needsauth():
    '''A decorator that sets auth.require config
    variable.'''

    def decorate(f):
        if not hasattr(f, '_cp_config'):
            f._cp_config = dict()
        if 'auth.require' not in f._cp_config:
            f._cp_config['auth.require'] = []
        f._cp_config['auth.require'] = True
        return f

    return decorate


class main(object):
    _cp_config = {'tools.auth.on': True,}
    @cherrypy.expose
    @needsauth()
    def myfunction(self):
        print 1
        return '<html>Hi</html>'

cherrypy.quickstart(main())