Digest authentication in Python?
Asked Answered
C

2

9

I'm trying to access pages from my company server with python. The first trail return 401: Unathorized(the server does need domain username/pwd for authentication). And the header content is as follow, and it seems to support 3 authentication protocols, Negotiate, NTLM and Digest, so in my understanding, I can choose any of them, right?

Content-Type: text/html
Server: Microsoft-IIS/7.0
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
WWW-Authenticate: Digest qop="auth",algorithm=MD5-sess,nonce="+Upgraded+v184080dc2d18fe10d63520db505929b5b5b929ec98692ce010e80d6347b7a35d4027e59e277ac4fe1c257a95196071258a8e0797bf6129f76",charset=utf-8,realm="Digest"
X-Powered-By: ASP.NET
Date: Tue, 06 Aug 2013 09:24:44 GMT
Connection: close
Content-Length: 1293
Set-Cookie: LB-INFO=1065493258.20480.0000; path=/

I'm using following python codes, but still got 401 unanthorized error, can anybody tell me how can i achieve it? Should I use NTLM? Thanks in advance!

p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, self.url, username, password)
handler = urllib2.HTTPDigestAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

f = opener.open(self.url)
Confined answered 6/8, 2013 at 14:58 Comment(0)
M
7

urllib2 is the python standard library, but not necessarily the best tool for HTTP Requests.

I would highly recommend checking out the requests package, and you can find an authentication tutorial here: http://docs.python-requests.org/en/latest/user/authentication/#digest-authentication

Mitchiner answered 6/8, 2013 at 15:1 Comment(1)
Thanks, I made it using requests! requests.get(url,auth=HttpNtlmAuth('domain\\username',pwd))Confined
E
17

Another very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:

from requests.auth import HTTPDigestAuth
url = 'http://httpbin.org/digest-auth/auth/user/pass'
requests.get(url, auth=HTTPDigestAuth('user', 'pass'))

Esthete answered 13/4, 2018 at 9:23 Comment(2)
This should be the accepted answerFat
Thanks for this tip. This is exactly what I needed to send requests to my crappy Amcrest wireless security camera. I was struggling for a couple of hours until I found this. The API said something about 'Digest Authentication' which led me to search for that.Fisherman
M
7

urllib2 is the python standard library, but not necessarily the best tool for HTTP Requests.

I would highly recommend checking out the requests package, and you can find an authentication tutorial here: http://docs.python-requests.org/en/latest/user/authentication/#digest-authentication

Mitchiner answered 6/8, 2013 at 15:1 Comment(1)
Thanks, I made it using requests! requests.get(url,auth=HttpNtlmAuth('domain\\username',pwd))Confined

© 2022 - 2024 — McMap. All rights reserved.