Skip to content

Commit

Permalink
Patch 1 (#891)
Browse files Browse the repository at this point in the history
* Update jwks_client.py

Added support for providing an ssl.SSLContext (custom CA etc.)

* typo fix

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* added some test cases

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
juur and pre-commit-ci[bot] committed Jun 13, 2023
1 parent 7f07d50 commit 6cef6f2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
7 changes: 6 additions & 1 deletion jwt/jwks_client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import urllib.request
from functools import lru_cache
from ssl import SSLContext
from typing import Any, Dict, List, Optional
from urllib.error import URLError

Expand All @@ -20,13 +21,15 @@ def __init__(
lifespan: int = 300,
headers: Optional[Dict[str, Any]] = None,
timeout: int = 30,
ssl_context: Optional[SSLContext] = None,
):
if headers is None:
headers = {}
self.uri = uri
self.jwk_set_cache: Optional[JWKSetCache] = None
self.headers = headers
self.timeout = timeout
self.ssl_context = ssl_context

if cache_jwk_set:
# Init jwt set cache with default or given lifespan.
Expand All @@ -48,7 +51,9 @@ def fetch_data(self) -> Any:
jwk_set: Any = None
try:
r = urllib.request.Request(url=self.uri, headers=self.headers)
with urllib.request.urlopen(r, timeout=self.timeout) as response:
with urllib.request.urlopen(
r, timeout=self.timeout, context=self.ssl_context
) as response:
jwk_set = json.load(response)
except (URLError, TimeoutError) as e:
raise PyJWKClientConnectionError(
Expand Down
20 changes: 20 additions & 0 deletions tests/test_jwks_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import contextlib
import json
import ssl
import time
from unittest import mock
from urllib.error import URLError
Expand Down Expand Up @@ -335,3 +336,22 @@ def test_get_jwt_set_timeout(self):
jwks_client.get_jwk_set()

assert 'Fail to fetch data from the url, err: "timed out"' in str(exc.value)

def test_get_jwt_set_sslcontext_default(self):
url = "https://dev-87evx9ru.auth0.com/.well-known/jwks.json"
jwks_client = PyJWKClient(url, ssl_context=ssl.create_default_context())

jwk_set = jwks_client.get_jwk_set()

assert jwk_set is not None

def test_get_jwt_set_sslcontext_no_ca(self):
url = "https://dev-87evx9ru.auth0.com/.well-known/jwks.json"
jwks_client = PyJWKClient(
url, ssl_context=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)
)

with pytest.raises(PyJWKClientError):
jwks_client.get_jwk_set()

assert "Failed to get an expected error"

0 comments on commit 6cef6f2

Please sign in to comment.