verify jwt (access_token) by python

bar c 0 Reputation points
2023-11-07T15:17:15.7033333+00:00

hello, I have a front in angular and a backend in Django Python.
I take my access_token from my front by:

this.msalService.instance.acquireTokenSilent

and send it to my backend api, i need to verify and validate this access_token before anything will happen in my backend (so no one will fake a jwt access_token of an admin or other user).
how do i verify this access_token that is a jwt and how can i validate the access_token with my app register in Azure Microsoft?
thanks for the help

Access Development
Access Development
Access: A family of Microsoft relational database management systems designed for ease of use.Development: The process of researching, productizing, and refining new or existing technologies.
822 questions
Microsoft Entra External ID
Microsoft Entra External ID
A modern identity solution for securing access to customer, citizen and partner-facing apps and services. It is the converged platform of Azure AD External Identities B2B and B2C. Replaces Azure Active Directory External Identities.
2,648 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,536 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Akshay-MSFT 16,026 Reputation points Microsoft Employee
    2023-11-08T07:46:50.4566667+00:00

    @bar c

    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.