【问题标题】:Generate authorization digest header with urllib2 or requests使用 urllib2 或请求生成授权摘要标头
【发布时间】:2014-01-16 18:59:54
【问题描述】:

我正在尝试生成摘要授权标头以用于 python 测试用例。由于代码库的工作方式,我能够将标题作为字符串获取是很重要的。 这个标题看起来像这样

Authorization: Digest username="the_user", realm="my_realm", nonce="1389832695:d3c620a9e645420228c5c7da7d228f8c", uri="/some/uri", response="b9770bd8f1cf594dade72fe9abbb2f31"

我认为我最好的选择是使用 urllib2 或 requests 库。

使用 urllib2,我已经走到了这一步:

au=urllib2.HTTPDigestAuthHandler()
au.add_password("my_realm", "http://example.com/", "the_user", "the_password")

但我无法从中获取标题。

有了请求,我已经走到了这一步:

requests.HTTPDigestAuth("the_user", "the_password")

但是当我尝试在请求中使用它时,我在设置领域时遇到错误,我不知道该怎么做

【问题讨论】:

    标签: python urllib2 python-requests digest-authentication


    【解决方案1】:

    如果你准备在它周围扭曲自己,你可以让requests.auth.HTTPDigestAuth 类通过执行以下操作为你提供正确答案:

    from requests.auth import HTTPDigestAuth
    
    chal = {'realm': 'my_realm', 'nonce': '1389832695:d3c620a9e645420228c5c7da7d228f8c'}
    a = HTTPDigestAuth('the_user', password)
    a.chal = chal
    
    print a.build_digest_header('GET', '/some/uri')
    

    如果我使用'the_password' 作为用户的密码,那么结果如下:

    Digest username="the_user", realm="my_realm", nonce="1389832695:d3c620a9e645420228c5c7da7d228f8c", uri="/some/uri", response="0b34daf411f3d9739538c7e7ee845e92"
    

    【讨论】:

    • 我在生成随机数时遇到了一些问题。我发现了这个:md5("%d:%s" % (time.time(), 'the_realm')).hexdigest()},但这似乎不起作用。
    • 你最后得到了一个无与伦比的大括号。
    • 看起来你应该只对领域进行 MD5,而不是整个字符串。所以适当的字符串应该是:`"%d:%d" % (time.time(), md5('the_realm').hexdigest())
    猜你喜欢
    • 2019-01-01
    • 2016-06-03
    • 2016-12-04
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 2015-06-30
    相关资源
    最近更新 更多