5

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 ?

jww
  • 97,681
  • 90
  • 411
  • 885
Bigmyx
  • 131
  • 2
  • 12
  • Seems a duplicate of https://stackoverflow.com/questions/5319430/how-do-i-have-python-httplib-accept-untrusted-certs – eel ghEEz Mar 16 '18 at 17:38

2 Answers2

5

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)
Andrew
  • 25
  • 5
Eric Tsui
  • 1,924
  • 12
  • 21
  • I could use `urllib2.urlopen`, but I don't know how to add cookies to the request other than via opener object. – Bigmyx Jun 17 '15 at 23:13
3

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)

Tomuo
  • 141
  • 1
  • 6