how to verify azure access token gotten from client web app and sent to python server

Jonathan okorie 20 Reputation points
2024-04-28T02:59:36.8366667+00:00

I get an azure access token from my client SPA (single page application) using MSAL (Microsoft authentication library) as a public client application. I then send the access token received after successful authentication to my python server by including it in the Authorization bearer header of the request, my question now is how do i verify this access token in my python server ??

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,856 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,679 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,865 questions
0 comments No comments
{count} votes

Accepted answer
  1. 2024-04-29T04:34:46.5433333+00:00

    Use python-jose to do something like this:

    		# Fetch the OpenID configuration, which includes the JWKS
            response = requests.get("your_tenant_openidc_configuration_endpoint_url") # Eg. 
    https://login.microsoftonline.com/tenant-guid/v2.0/.well-known/openid-configuration
            payload = response.json()
            jwks = payload["jwks_uri"]
            issuer = payload["issuer"]
    
    		# Decode the JWT token (without verification)
            unverified_header = jwt.get_unverified_header(token_string)
    
            response = requests.get(jwks)
            keys = response.json().get("keys")
    
            # Find the key which was used to sign the JWT token
            rsa_key = {}
    
            for key in keys:
                if key["kid"] == unverified_header["kid"]:
                    rsa_key = {
                        "kty": key["kty"],
                        "kid": key["kid"],
                        "use": key["use"],
                        "n": key["n"],
                        "e": key["e"],
                    }
    
            # Verify the JWT token
    		payload = jwt.decode(
            	token_string,
                rsa_key,
                algorithms=["RS256"],
                audience="your_api_client_id",
                issuer=issuer,
                options=options,
    		)
            return payload
    

    Let me know if you need additional or more detailed guidance. If the answer was helpful, please accept it and rate it so that others facing a similar issue can easily find a solution.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful