scottmrogowski
scottmrogowski

Reputation: 2123

Generate authorization digest header with urllib2 or requests

I am trying to generate the digest authorization header for use in a python test case. Because of the way the code base works, it is important that I am able to get the header as a string. This header looks something like this

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.

With urllib2, I have gotten this far:

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.

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

Upvotes: 3

Views: 2963

Answers (2)

Yinon_90
Yinon_90

Reputation: 1745

When I tried @Lukasa answer I got an error:

'_thread._local' object has no attribute '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'))

Upvotes: 0

Lukasa
Lukasa

Reputation: 15558

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:

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:

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

Upvotes: 4

Related Questions