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 Security | Microsoft Entra | Microsoft Entra External ID
Microsoft Security | Microsoft Entra | Microsoft Entra ID
Microsoft Security | Microsoft Graph
0 comments No comments
{count} votes

Accepted answer
  1. Alfredo Revilla - Upwork Top Talent | IAM SWE SWA 27,526 Reputation points Moderator
    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.