From 4b7873cabd459fb9e1d20e0f658eb71ed3e53278 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Cresson?= Date: Wed, 12 Apr 2023 17:04:22 +0200 Subject: [PATCH] Get roles from client (#75) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ENH: get roles from client * Retrieve client role using azp * Retrieve client role using azp --------- Co-authored-by: Yannic Schröer --- fastapi_keycloak/model.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/fastapi_keycloak/model.py b/fastapi_keycloak/model.py index 0bc1a07..67289a4 100644 --- a/fastapi_keycloak/model.py +++ b/fastapi_keycloak/model.py @@ -97,6 +97,7 @@ class OIDCUser(BaseModel): details. This is a mere proxy object. """ + azp: Optional[str] sub: str iat: int exp: int @@ -118,18 +119,26 @@ def roles(self) -> List[str]: Returns: List[str]: If the realm access dict contains roles """ - if not self.realm_access: + if not self.realm_access and not self.resource_access: raise KeycloakError( status_code=404, - reason="The 'realm_access' section of the provided access token is missing", + reason="The 'realm_access' and 'resource_access' sections of the provided access token are missing.", ) - try: - return self.realm_access["roles"] - except KeyError as e: + roles = [] + if self.realm_access: + if "roles" in self.realm_access: + roles += self.realm_access["roles"] + if self.azp and self.resource_access: + if self.azp in self.resource_access: + if "roles" in self.resource_access[self.azp]: + roles += self.resource_access[self.azp]["roles"] + if not roles: raise KeycloakError( status_code=404, - reason="The 'realm_access' section of the provided access token did not contain any 'roles'", - ) from e + reason="The 'realm_access' and 'resource_access' sections of the provided access token did not " + "contain any 'roles'", + ) + return roles def __str__(self) -> str: """String representation of an OIDCUser"""