How to validate access token from AzureAD in python? – Python

by
Ali Hasan
azure-ad-msal fastapi jwt llama-cpp-python single-sign-on

The Problem:

In a backend service, how can we securely validate an access token issued by Azure Active Directory (Azure AD) from a frontend application? Specifically, what are the recommended libraries or methods to use for verifying the authenticity of the token?

The Solutions:

Solution : Microsoft does not have a Python Library

To validate the access token in backend , you can use the following steps :

Step one : Import the required Libraries

In your backend code , Import the required Libraries to manipulate and validate the access tokens :

import requests
from jose import jwt

Step two : Extract Access token

To extract the access token , you can use the request object like this

access token = request .headers['Authorization']

Step three : Decode JWT Token

Use the JWT library to decode the received access token .Make sure to verify its validity by checking the issuer and audience :

decoded = jwt . decode (access token ,'your secret key ',algorithms = ['RS','ES','HS'])

Step four : Verify the issuer and Audience field

Verify the issuer (iss) and audience (aud) of the token to ensure that they match the expected values :

if decoded['iss'] != 'your issuer URL':
    return {"message":" invalid issuer"}, "code": "Invalid", "status":status.''Forbidden''
if decoded['aud'] != 'your audience URL':
    return   {"message":" invalid audience"},'' code ':''Invalid'', 'status':''Forbidden''

Step five : Check the expiration time

Validate the expiration time (exp) of the token to ensure that it is not expired :

now = time . time ()
if now >decoded['exp']:
    return {"message":" Token expired ", 'code':' Expired', 'status': 'Forbidden'}

Step Six : Return Validation Result

Depending on the results of the validation checks , return an appropriate response , such as ‘Valid ‘or ‘Invalid ‘ token .

return {"message":" Token Valid ", 'code': 'Valid', 'status': 'OK'}

Solution 2: Using JWT and Cryptography Libraries

This solution utilizes `PyJWT` and `cryptography` libraries to validate AzureAD access tokens. Here’s a detailed breakdown:

  1. Obtain JWKS and Unverified Header:
    – `jwks_url` contains the location of the JSON Web Key Set (JWKS) containing public keys for verification.
    – `issuer_url` and `audience` are adjusted to match the AzureAD setup.
    – `jwks` is loaded from the JWKS URL.
    – The unverified header `unverified_header` is extracted from the access token.
  2. Locate RSA Key:
    – The function `find_rsa_key` searches for the RSA key corresponding to the `kid` in the unverified header.
  3. Convert RSA Key to PEM Format:
    – `rsa_pem_from_jwk` converts the RSA key to PEM format, which is compatible with `PyJWT`.
  4. Validate Access Token:
    – `jwt.decode()` is used to validate the access token with the following parameters:
    – `public_key`: The RSA public key in PEM format.
    – `verify`: Set to `True` to perform signature verification.
    – `algorithms`: The algorithm used to sign the token, typically “RS256”.
    – `audience`: The expected audience for the token.
    – `issuer`: The expected issuer for the token.

This solution ensures secure validation of AzureAD access tokens by verifying signatures and matching relevant claims against the configured issuer and audience. It follows the approach outlined in Roberto Prevato’s blog post.

Q&A

How to validate access token with backend in python?

Microsoft does not provide a library to validate access tokens in Python. However, there is an official sample showing how to validate the access token.

Is there a Python library for validating access tokens?

Yes, you can find some useful libraries such as PyJWT and cryptography.

Video Explanation:

The following video, titled "Authenticating to Azure Using Python - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

API Authentication with OAuth using Azure AD. Azure Power Lunch•102K ... Azure SDK DefaultAzureCredential : Unifying How We Get Azure AD Token.