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

Commit

Permalink
Get roles from client (#75)
Browse files Browse the repository at this point in the history
* ENH: get roles from client

* Retrieve client role using azp

* Retrieve client role using azp

---------

Co-authored-by: Yannic Schröer <[email protected]>
  • Loading branch information
remicres and yannicschroeer authored Apr 12, 2023
1 parent 2f6c0af commit 4b7873c
Showing 1 changed file with 16 additions and 7 deletions.
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

0 comments on commit 4b7873c

Please sign in to comment.