Skip to content
This repository has been archived by the owner on Mar 16, 2024. It is now read-only.

Get roles from client #75

Merged
merged 5 commits into from
Apr 12, 2023
Merged
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
23 changes: 16 additions & 7 deletions fastapi_keycloak/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ class OIDCUser(BaseModel):
details. This is a mere proxy object.
"""

azp: Optional[str]
sub: str
iat: int
exp: int
Expand All @@ -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"""
Expand Down