Skip to content

Commit 7eb6b63

Browse files
✨ [#403] Support cafile and capath parameters (#415)
When retrieving the IDP metadata, you can now optionally specify the the capath or cafile to use for certificate verification, rather than just enabling/disabling it. This allows TLS verification of server certificates that are not in the system root store (such as when using private CAs).
1 parent 27372ce commit 7eb6b63

File tree

2 files changed

+22
-16
lines changed

2 files changed

+22
-16
lines changed

src/onelogin/saml2/idp_metadata_parser.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,7 @@
66

77

88
from copy import deepcopy
9-
10-
try:
11-
import urllib.request as urllib2
12-
except ImportError:
13-
import urllib2
9+
from urllib.request import Request, urlopen
1410

1511
import ssl
1612

@@ -27,7 +23,15 @@ class OneLogin_Saml2_IdPMetadataParser(object):
2723
"""
2824

2925
@classmethod
30-
def get_metadata(cls, url, validate_cert=True, timeout=None, headers=None):
26+
def get_metadata(
27+
cls,
28+
url,
29+
validate_cert=True,
30+
cafile=None,
31+
capath=None,
32+
timeout=None,
33+
headers=None,
34+
):
3135
"""
3236
Gets the metadata XML from the provided URL
3337
:param url: Url where the XML of the Identity Provider Metadata is published.
@@ -46,15 +50,20 @@ def get_metadata(cls, url, validate_cert=True, timeout=None, headers=None):
4650
"""
4751
valid = False
4852

49-
request = urllib2.Request(url, headers=headers or {})
50-
51-
if validate_cert:
52-
response = urllib2.urlopen(request, timeout=timeout)
53-
else:
53+
# Respect the no-TLS-certificate validation option
54+
ctx = None
55+
if not validate_cert:
56+
if cafile or capath:
57+
raise ValueError(
58+
"Specifying 'cafile' or 'capath' while disabling certificate "
59+
"validation is contradictory."
60+
)
5461
ctx = ssl.create_default_context()
5562
ctx.check_hostname = False
5663
ctx.verify_mode = ssl.CERT_NONE
57-
response = urllib2.urlopen(request, context=ctx, timeout=timeout)
64+
65+
request = Request(url, headers=headers or {})
66+
response = urlopen(request, timeout=timeout, cafile=cafile, capath=capath, context=ctx)
5867
xml = response.read()
5968

6069
if xml:

tests/src/OneLogin/saml2_tests/idp_metadata_parser_test.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33

4-
try:
5-
from urllib.error import URLError
6-
except ImportError:
7-
from urllib2 import URLError
4+
from urllib.error import URLError
85

96
from copy import deepcopy
107
import json

0 commit comments

Comments
 (0)