Skip to content

Commit a03b36c

Browse files
authored
api_jwk: Add PyJWKSet.__getitem__ (#725)
* api_jwk: Add PyJWKSet.__getitem__ Closes #724. * CHANGELOG: record changes
1 parent 77d7916 commit a03b36c

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ Fixed
1616
Added
1717
~~~~~
1818

19+
- Add ``PyJWKSet.__getitem__`` for indexing keysets by key ID `#725 <https://github.com/jpadilla/pyjwt/pull/725>`__
20+
1921
`v2.3.0 <https://github.com/jpadilla/pyjwt/compare/2.2.0...2.3.0>`__
2022
-----------------------------------------------------------------------
2123

jwt/api_jwk.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,9 @@ def from_dict(obj):
9595
def from_json(data):
9696
obj = json.loads(data)
9797
return PyJWKSet.from_dict(obj)
98+
99+
def __getitem__(self, kid):
100+
for key in self.keys:
101+
if key.key_id == kid:
102+
return key
103+
raise KeyError("keyset has no key for kid: %s" % kid)

tests/test_api_jwk.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,3 +252,26 @@ def test_should_load_keys_from_jwk_data_json_string(self):
252252
assert jwk.key_type == "RSA"
253253
assert jwk.key_id == "keyid-abc123"
254254
assert jwk.public_key_use == "sig"
255+
256+
@crypto_required
257+
def test_keyset_should_index_by_kid(self):
258+
algo = RSAAlgorithm(RSAAlgorithm.SHA256)
259+
260+
with open(key_path("jwk_rsa_pub.json")) as keyfile:
261+
pub_key = algo.from_jwk(keyfile.read())
262+
263+
key_data_str = algo.to_jwk(pub_key)
264+
key_data = json.loads(key_data_str)
265+
266+
# TODO Should `to_jwk` set these?
267+
key_data["alg"] = "RS256"
268+
key_data["use"] = "sig"
269+
key_data["kid"] = "keyid-abc123"
270+
271+
jwk_set = PyJWKSet.from_dict({"keys": [key_data]})
272+
273+
jwk = jwk_set.keys[0]
274+
assert jwk == jwk_set["keyid-abc123"]
275+
276+
with pytest.raises(KeyError):
277+
jwk_set["this-kid-does-not-exist"]

0 commit comments

Comments
 (0)