# -*- coding: utf-8 -*- import sys import urllib2 import ssl URL = 'http://example.com' USERNAME = 'apitest' PASSWORD = 'apitest' request = urllib2.Request(URL) context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) # fails with 'urllib2.HTTPError: HTTP Error 401: Unauthorized' urllib2.urlopen(request, context=context) # workaound: password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, URL, USERNAME, PASSWORD) http_handler = urllib2.HTTPHandler() https_handler = urllib2.HTTPSHandler(context=context) auth_handler = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(http_handler, https_handler, auth_handler) urllib2.install_opener(opener) # works opener.open(request)