user1935336
user1935336

Reputation:

Add SSL CA File Using urllib2

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 ?

Upvotes: 5

Views: 10233

Answers (2)

Eric Tsui
Eric Tsui

Reputation: 1924

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)

Upvotes: 5

Tomuo
Tomuo

Reputation: 141

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)

Upvotes: 3

Related Questions