Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allows passing of ssl.SSLContext to PyJWKClient #891

Merged
merged 6 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
Loading