urllib2 and HTTPBasicAuthHandler

m.banaouas banaouas.medialog at wanadoo.fr
Tue Jan 16 17:06:53 CET 2007


Hi all,
I started to use urllib2 library and HTTPBasicAuthHandler class in order 
to authenticate with a http server (Zope in this case).
I don't know why but it doesn't work, while authenticating with direct 
headers manipulation works fine!

WinXP Sp2
Python 2.4.4

Thanks in advance for your help/comments

# TestAuthHandler.py
import base64, httplib, urllib2
httplib.HTTPConnection.debuglevel = 1
#
def TestAuth(method):
   data = 
{'prot':'http','user':'admin','pass':'xxxxxx','host':'localhost','port':'8080','path':'manage','realm':'Zope'}
   url = '%(prot)s://%(host)s:%(port)s/%(path)s' % data
   req = urllib2.Request(url)
   #
   if (method == 'headers'):
     base64string = base64.encodestring('%s:%s' % (data['user'], 
data['pass']))[:-1]
     req.add_header("Authorization", "Basic %s" % base64string)
   elif  (method == 'handler'):
     auth_url = '%(host)s:%(port)s/%(path)s' % data
     auth_handler = urllib2.HTTPBasicAuthHandler()
     auth_handler.add_password(data['realm'], auth_url, data['user'], 
data['pass'])
     opener = urllib2.build_opener(auth_handler)
     urllib2.install_opener(opener)
   #
   f = urllib2.urlopen(req)
   data = f.read()
   print data
#
TestAuth('headers')
TestAuth('handler')
-------------------------
output:
-------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" 
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>Zope on http://localhost:8080</title>
</head>
... all right page ...
</html>


Traceback (most recent call last):
   File "C:\Test\TestAuthHandler.py", line 25, in ?
     TestAuth('handler')
   File "C:\Test\TestAuthHandler.py", line 20, in TestAuth
     f = urllib2.urlopen(req)
   File "C:\Python\Lib\urllib2.py", line 130, in urlopen
     return _opener.open(url, data)
   File "C:\Python\Lib\urllib2.py", line 364, in open
     response = meth(req, response)
   File "C:\Python\Lib\urllib2.py", line 471, in http_response
     response = self.parent.error(
   File "C:\Python\Lib\urllib2.py", line 402, in error
     return self._call_chain(*args)
   File "C:\Python\Lib\urllib2.py", line 337, in _call_chain
     result = func(*args)
   File "C:\Python\Lib\urllib2.py", line 480, in http_error_default
     raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized

Process "Python" completed with Exit Code 1, at 16/01/2007 16:51:18.



More information about the Python-list mailing list