Thank you for posting your query on Microsoft Q&A, from above description I could understand that you are looking for a way to validate Entra ID JWT tokens and API permissions via python.
Please do correct me if this is not the case:
We don't have a predefined sample or API code to this, however we have a sample fastAPI repo for reference. The Microsoft Identity library for Python's FastAPI provides Azure Active Directory token authentication and authorization through a set of convenience functions. It enables any FastAPI applications to authenticate with Azure AD to validate JWT tokens and API permissions.
Kindly refer to fastapi_microsoft_identity/auth_service.py for token validation part and you may use if with your API.
Example:
For validation of scp or scope:
def validate_scope(required_scope:str, request: Request):
has_valid_scope = False
token = get_token_auth_header(request);
unverified_claims = jwt.get_unverified_claims(token)
## check to ensure that either a valid scope or a role is present in the token
if unverified_claims.get("scp") is None and unverified_claims.get("roles") is None:
raise AuthError("IDW10201: No scope or app permission (role) claim was found in the bearer token", 403)
is_app_permission = True if unverified_claims.get("roles") is not None else False
if is_app_permission:
if unverified_claims.get("roles"):
# the roles claim is an array
for scope in unverified_claims["roles"]:
if scope.lower() == required_scope.lower():
has_valid_scope = True
else:
raise AuthError("IDW10201: No app permissions (role) claim was found in the bearer token", 403)
else:
if unverified_claims.get("scp"):
# the scp claim is a space delimited string
token_scopes = unverified_claims["scp"].split()
for token_scope in token_scopes:
if token_scope.lower() == required_scope.lower():
has_valid_scope = True
else:
raise AuthError("IDW10201: No scope claim was found in the bearer token", 403)
if is_app_permission and not has_valid_scope:
raise AuthError(f'IDW10203: The "role" claim does not contain role {required_scope} or was not found', 403)
elif not has_valid_scope:
raise AuthError(f'IDW10203: The "scope" or "scp" claim does not contain scopes {required_scope} or was not found', 403)
Thanks,
Akshay Kaushik
Please "Accept the answer" (Yes), and share your feedback if the suggestion answers you’re your query. This will help us and others in the community as well.