Add SSL CA File Using urllib2

10k Views Asked by At

I need to be able to specify SSL certificate CA root, yet be able to insert HTTP cookie with Python 2.7.10 urllib2 library

ssl_handler = urllib2.HTTPSHandler()
opener = urllib2.build_opener(ssl_handler)
opener.addheaders.append(("Cookie","foo=blah"))
res = opener.open(https://example.com/some/info)

I know urllib2 supports cafile param, where should I use it in my code ?

2

There are 2 best solutions below

1
On

urlopen documentation:

urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

so, please try:

urllib2.urlopen("https://example.com/some/info", cafile="test_cert.pem")

or

cxt = ssl.create_default_context(cafile="/path/test_cert.pem")
urllib2.urlopen("https://example.com/some/info", context=cxt)
0
On

The ability to specify a CA file was added in python 2.7.9, according to the documentation, and is only available in the urlopen call, as as noted in the previous answer.

So you do need to change opener.open() to urllib2.urlopen. In order to have it still use the opener, call urllib2.install_opener(opener) before the urlopen call

This is the only way I found to have all of (cookies & login authentication & CA cert specified)