Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python urllib2 basic authentication

Tags:

python

urllib2

Hi i'm trying to use python to access an API URL using urllib2:

import urllib2

url = 'https://XXXXXXXXXX.com/'
username = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
password = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(url)

I don't know what the realm is but am assuming I can use default i.e. None.

Anyway, i am still get 401 error:

Traceback (most recent call last): File "test5.py", line 12, in pagehandle = urllib2.urlopen(url) File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.6/urllib2.py", line 397, in open response = meth(req, response) File "/usr/lib/python2.6/urllib2.py", line 510, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.6/urllib2.py", line 435, in error return self._call_chain(*args) File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib/python2.6/urllib2.py", line 518, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized

so it seems there is something wrong with the authentication. Is it most likely the use of realm = None?

Thanks!

like image 934
2one Avatar asked Aug 30 '13 13:08

2one


1 Answers

I could not figure out why this method did not work but I was successful in calling the API using this code:

base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

request = urllib2.Request(url)

request.add_header("Authorization", "Basic %s" % base64string) 

result = urllib2.urlopen(request)
        data = result.read()
like image 182
2one Avatar answered Oct 05 '22 02:10

2one