urllib2 Basic authentication, what am I doing wrong?

7stud bbxx789_05ss at yahoo.com
Sun Apr 13 23:23:48 CEST 2008


Michel Bouwmans wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hey everybody,
>
> I'm having a little problem with urllib2 and Basic HTTP authentication.
>
> I have the following code:
>
> auth = urllib2.HTTPPasswordMgrWithDefaultRealm()
> auth.add_password(None, 'https://webmail.osg-erasmus.nl/oneNet/NetStorage/',
> user, password)
> authhandler = urllib2.HTTPBasicAuthHandler(auth)
>
> opener = urllib2.build_opener(auth)
> opener.addheaders = [('User-agent', 'Mozilla/5.0 Something/1.0')]
>
> try:
>         return
> self.opener.open('https://webmail.osg-erasmus.nl/oneNet/NetStorage/')
> except urllib2.HTTPError, e:
>         print e.code
>         print e.headers
>
> This however does not allow me to authenticate. I keep getting back a 401:
>
> 401
> Date: Sun, 13 Apr 2008 18:11:32 GMT
> Server: Apache/2.0.54 (NETWARE) mod_perl/1.99_12 Perl/v5.8.4 PHP/5.0.5
> mod_nsn/1.0_0 mod_jk/1.2.14
> Set-Cookie: novellsession1=8KuAO0iLyAEAAAAAAAAAAA==; path=/
> WWW-Authenticate: Basic realm="ERASMUS-TREE"
> Vary: accept-language,accept-charset
> Accept-Ranges: bytes
> Connection: close
> Transfer-Encoding: chunked
> Content-Type: text/html; charset=iso-8859-1
> Content-Language: en
>
> Using this nice class (adapted to urllib2) as a basehandler I see that no
> Authentication-header is being send out:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440574
>
> What am I doing wrong here? I spend almost my entire free time today on this
> and couldn't find any problem with my code, anyone else has a thought?
> Thanks in advance.


Can you get something like the following to work:

import urllib2

pword_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
pword_manager.add_password(None, 'http://localhost/
pwordProtectedStuff/', 'jane', 'janes_password')

authentication_handler = urllib2.HTTPBasicAuthHandler(pword_manager)
my_custom_urlopen_function =
urllib2.build_opener(authentication_handler)
urllib2.install_opener(my_custom_urlopen_function)

f = urllib2.urlopen('http://localhost/pwordProtectedStuff/test.htm')
print f.read()



More information about the Python-list mailing list