Unable to acquire token using client certificate authentication in Python

141 Views Asked by At

To obtain a token with client secret authentication, we followed these steps:

  • Registered an application in the Azure portal and got the client ID and client secret.
  • Added Microsoft Graph permissions with administrator consent
from msal import ConfidentialClientApplication
client_id = "xxxxxx"
client_secret = "yyyyyyy"
tenant_id = "zzzzzzz"
authority_url = f"https://login.microsoftonline.com/{tenant_id}"
app = ConfidentialClientApplication(
    client_id=client_id,
    client_credential=client_secret,
    authority=authority_url
)
scope = "https://graph.microsoft.com/.default"
result = app.acquire_token_for_client(scopes=scope)
access_token = result.get("access_token")
print(access_token)

We are looking for a way to use client certificate authentication instead of client secret, but we cannot find any Python code that works.

enter image description here

1

There are 1 best solutions below

0
Sridevi On BEST ANSWER

I registered one Entra ID application and added permissions with consent as below:

enter image description here

Now, I ran below commands to create private key and certificate like this:

openssl genrsa -out sridemo.pem 2048
openssl req -new -key sridemo.pem -out sridemo.csr
openssl x509 -req -days 365 -in sridemo.csr -signkey sridemo.pem -out sridemo.crt

Response:

enter image description here

When I checked the folder in that path, files created successfully like this:

enter image description here

Now, upload sridemo.crt file to your Entra ID app registration and note thumbprint value:

enter image description here

To generate the access token using client certificate, make use of below sample Python code:

from msal import ConfidentialClientApplication

tenant_id = "your_tenant_id"
client_id = "your_client_id"
authority = f"https://login.microsoftonline.com/{tenant_id}"

certificate_path = "path/to/your/certificate.pem"
certificate_thumbprint = "your_certificate_thumbprint"

scope = "https://graph.microsoft.com/.default"

app = ConfidentialClientApplication(
    client_id,
    authority=authority,
    client_credential={"thumbprint": certificate_thumbprint, "private_key": open(certificate_path).read()},
)

token_response = app.acquire_token_for_client(scopes=[scope])
access_token = token_response.get("access_token")

print("Access Token:", access_token)

Response:

enter image description here

When I decoded the above token in jwt.ms, I got aud and roles claims with valid values like this:

enter image description here

Reference: Client credentials - Microsoft Authentication Library for Python | Microsoft