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)

2 Answers 2

18

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'))

Sign up to request clarification or add additional context in comments.

2 Comments

This should be the accepted answer
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.
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

1 Comment

Thanks, I made it using requests! requests.get(url,auth=HttpNtlmAuth('domain\\username',pwd))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.