urllib2 and HTTPBasicAuthHandler

m.banaouas banaouas.medialog at wanadoo.fr
Tue Jan 16 18:45:53 EST 2007


Max,
I verified and determined that Zope realm is "Zope", by tcp spy tool 
witch shows me the server headers.
Actually, I tried differents ways without success.
It seems like it's not so easy to negociate a basic authentication 
process with urllib2, while it's based on very simple specifications, 
however urllib2 is considered as one of the most powerfull library in 
its category.

You suggest to use default realm:
   # this creates a password manager
   passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
   # because we have put None at the start it will always use this 
username/password combination
   passman.add_password(None, auth_url, data['user'] , data['pass'])
   # create the AuthHandler
   auth_handler = urllib2.HTTPBasicAuthHandler(passman)
   # build an 'opener' using the handler we've created
   opener = urllib2.build_opener(auth_handler)
   urllib2.install_opener(opener)
   req = urllib2.Request(url)
   f = urllib2.urlopen(req)
   data = f.read()
   print data
but it doesn't work: urllib2.HTTPError: HTTP Error 401: Unauthorized

Max Erickson a écrit :
> "m.banaouas" <banaouas.medialog at wanadoo.fr> wrote:
> 
>> 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!
>>
> ...
>> port':'8080','path':'manage','realm':'Zope'} 
>>    url = '%(prot)s://%(host)s:%(port)s/%(path)s' % data
> ...
> 
> Are you certain that the realm on the server matches 'Zope'?
> 
> HTTPBasicAuthHandler uses the realm to look for the password, if the 
> realm the server provides is different, urllib2 will respond as if it 
> does not have a user/password.
> 
> If you are only doing one request, it isn't that big a deal; if you 
> are doing many requests or want urllib2 to handle the response for 
> other reseans, you can use a default realm, see the bottom of this 
> example:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305288
> 
> (The advantage of using a default rather than making sure the realm is 
> correct is that it can change and you won't have to do anything)
> 
> 
> 
> max
> 



More information about the Python-list mailing list