Skip to content

Commit

Permalink
factory methods
Browse files Browse the repository at this point in the history
  • Loading branch information
byewokko committed Jan 23, 2025
1 parent ea305ef commit 407269a
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions asab/web/auth/providers/id_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import jwcrypto.jwk

from .abc import AuthProviderABC
from .key_provider import PublicKeyProviderABC, LocalPublicKeyProvider
from .key_provider import PublicKeyProviderABC, FilePublicKeyProvider
from ..utils import get_bearer_token_from_authorization_header, get_id_token_claims


Expand All @@ -24,11 +24,35 @@ def __init__(self, app, auth_service, public_key_providers: typing.Iterable[Publ
self.add_key_provider(provider)
self.Authorizations = {}

self.App.TaskService.schedule(self._update_public_keys())


def add_key_provider(self, provider: PublicKeyProviderABC):
self._set_ready(False)
self.KeyProviders.add(provider)


def add_jwks_url(self, jwks_url: str):
self._set_ready(False)
self.add_key_provider(
UrlPublicKeyProvider(self.App, self, jwks_url)
)


def add_public_key(self, public_key: jwcrypto.jwk.JWK | jwcrypto.jwk.JWKSet):
self._set_ready(False)
self.add_key_provider(
PublicKeyProvider(self.App, self, public_key)
)


def add_public_key_from_file(self, file_path: str, from_private_key: bool = False):
self._set_ready(False)
self.add_key_provider(
FilePublicKeyProvider(self.App, self, file_path, from_private_key)
)


async def initialize(self):
pass

Expand All @@ -45,8 +69,8 @@ async def _update_public_keys(self):
"""
jwks = jwcrypto.jwk.JWKSet()
for provider in self.KeyProviders:
await provider.update_public_keys()
jwks.add(provider.PublicKey)
await provider.reload_keys()
jwks.update(provider.PublicKeySet)

self.TrustedJwkSet = jwks

Expand Down Expand Up @@ -86,7 +110,7 @@ async def _get_claims_from_id_token(self, id_token):
if not self.is_ready():
# Try to load the public keys again
if not self.TrustedJwkSet["keys"]:
await self._fetch_public_keys_if_needed()
await self._update_public_keys()
if not self.is_ready():
L.error("Cannot authenticate request: Failed to load authorization server's public keys.")
raise aiohttp.web.HTTPUnauthorized()
Expand All @@ -95,7 +119,7 @@ async def _get_claims_from_id_token(self, id_token):
return get_id_token_claims(id_token, self.TrustedJwkSet)
except (jwcrypto.jws.InvalidJWSSignature, jwcrypto.jwt.JWTMissingKey):
# Authz server keys may have changed. Try to reload them.
await self._fetch_public_keys_if_needed()
await self._update_public_keys()

try:
return get_id_token_claims(id_token, self.TrustedJwkSet)
Expand Down

0 comments on commit 407269a

Please sign in to comment.