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"""