简体   繁体   English

使用 urllib2 或请求生成授权摘要 header

[英]Generate authorization digest header with urllib2 or requests

I am trying to generate the digest authorization header for use in a python test case.我正在尝试生成摘要授权 header 以用于 python 测试用例。 Because of the way the code base works, it is important that I am able to get the header as a string.由于代码库的工作方式,重要的是我能够将 header 作为字符串获取。 This header looks something like this这个 header 看起来像这样

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

I think my best bets are to use either urllib2 or the requests library.我认为我最好的选择是使用 urllib2 或 requests 库。

With urllib2, I have gotten this far:使用 urllib2,我已经做到了这一点:

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

but I can't get the header out of that.但我无法摆脱 header 。

With requests, I have gotten this far:有了请求,我已经做到了这一点:

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

But I when I try to use that, in a request, I am getting errors about setting the realm which I can't figure out how to do但是当我尝试使用它时,在请求中,我收到有关设置 realm 的错误,我不知道该怎么做

If you're prepared to contort yourself around it, you can get the requests.auth.HTTPDigestAuth class to give you the right answer by doing something like this: 如果您准备扭曲自己,可以通过执行以下操作来获取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')

If I use 'the_password' as the user's password, that gives me this result: 如果我使用'the_password'作为用户密码, 'the_password'得到以下结果:

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

When I tried @Lukasa answer I got an error:当我尝试@Lukasa 回答时出现错误:

'_thread._local' object has no attribute 'chal' '_thread._local' object 没有属性 'chal'

So I solved it in a slightly dirty way but it works:所以我以一种稍微肮脏的方式解决了它,但它有效:

from requests.auth import HTTPDigestAuth

chal = {'realm': 'my_realm',
        'nonce': '1389832695:d3c620a9e645420228c5c7da7d228f8c'}
a = HTTPDigestAuth("username", "password")
a.init_per_thread_state()
a._thread_local.chal = chal

print(a.build_digest_header('GET', '/some/uri'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM