python - CherryPy 身份验证超时

标签 python cherrypy

我向 CherryPy 服务器添加了摘要身份验证,我想知道撤销用户身份验证的标准是什么,并提示他们再次输入凭据。删除 cookie 不会强制出现提示,但使用隐身或其他浏览器会强制出现提示。

我的配置:

{ 'tools.auth_digest.on': True,
  'tools.auth_digest.realm': 'localhost',
  'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(USERS),
  'tools.auth_digest.key': key,
  'tools.auth_digest.accept_charset': 'UTF-8' }

谢谢

最佳答案

您需要有正确的 HTTP 响应,以便浏览器清除用户凭据,基本上以 401 Unauthorized 进行响应以及如何使用 WWW-Authenticate 进行身份验证的挑战 header 。

这是使用自定义 CherryPy 工具和 Cookie 的实现它被用作向浏览器和后端传达意图的方式(HTTP 身份验证是无状态的,我们必须来回解除身份验证和重定向)。

import cherrypy
from cherrypy.lib import auth_digest


REALM = 'localhost'
KEY = '24684651368351320asd1wdasd'
CHARSET = 'UTF-8'


@cherrypy.tools.register('before_handler')
def with_logout_handler():
    if cherrypy.request.cookie.get('Unauthorize') is not None:
        response = cherrypy.response
        response.headers['WWW-Authenticate'] = auth_digest.www_authenticate(
            realm=REALM,
            key=KEY,
            accept_charset=CHARSET
        )
        # delete the cookie that was used to mark the intention to logout
        response.cookie['Unauthorize'] = 1
        response.cookie['Unauthorize']['expires'] = 0
        raise cherrypy.HTTPError(
            401, 'You are not authorized to access that resource')


class App:
    @cherrypy.expose
    @cherrypy.tools.with_logout_handler()
    def index(self):
        return ('Welcome {}! Do you want to <a href="/logout">logout</a>?'
                .format(cherrypy.request.login))

    @cherrypy.expose
    def logout(self):
        """
        Set a cookie to give it a clue to the index method to
        remove the user credentials from the following requests.

        This will be handled by the tool `with_logout_handler`.
        """
        cherrypy.response.cookie['Unauthorize'] = 1
        raise cherrypy.HTTPRedirect("/")


def main():
    users = {
        'foo': 'bar'
    }
    cherrypy.quickstart(App(), config={
        '/': {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': REALM,
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
            'tools.auth_digest.key': KEY,
            'tools.auth_digest.accept_charset': CHARSET
        },
    })

if __name__ == '__main__':
    main()

关于python - CherryPy 身份验证超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57390780/

相关文章:

python - 在 cherrypy/mako 中使用动态参数处理 URL

python - 多处理在 Ubuntu 中有效,在 Windows 中无效

python - 如何派生带有修饰方法的类?

python - 将两个 Pandas 系列与不断变化的逻辑结合起来

python - 在循环中按索引对列表中的元素求和

python - Pandas 导入 FRED 数据(pandas.io.data 或 pandas_datareader)

python - 将嵌套的可迭代对象转换为列表

javascript - 模态框没有完全显示

python - 是什么导致 UnicodeEncodeError 异常潜入工作的 Python 环境?

python - 将 unicode 值(不带\u)映射到正确的解码字符串