How to set authority to request token for the Microsoft Graph API?

134 Views Asked by At

I am using azure.identity.aio python SDK to get access_token. For that I use ClientSecretCredential() class. This is current code that I have:

credential = ClientSecretCredential(tenant_id=tenant_id, client_secret=client_secret)
access_token = credential.get_token("{host}/.default".format(host=host))

But I get Confidential Client is not supported in Cross Cloud request error when I set national cloud host such as graph.microsoft.us. I guess, one option is explicitly setting the authority:

credential = ClientSecretCredential(tenant_id=tenant_id, client_secret=client_secret,authority=AzureAuthorityHosts.AZURE_GOVERNMENT)

But what if the login or api host is graph.microsoft.de or graph.microsoft.cn. Is there any way to dynamically set the authority based on the specified hostname?

1

There are 1 best solutions below

0
Sridevi On

You can make use of below python code to set authority dynamically based on specified hostname, while requesting token for MS Graph:

from azure.identity import ClientSecretCredential, AzureAuthorityHosts

def get_authority_for_host(host):
    # Map hosts to the corresponding authority URLs
    host_authority_mapping = {
        "graph.microsoft.us": AzureAuthorityHosts.AZURE_GOVERNMENT,
        "graph.microsoft.de": AzureAuthorityHosts.AZURE_GERMANY,
        "graph.microsoft.cn": AzureAuthorityHosts.AZURE_CHINA,
        # Add more mappings as needed
    }
    return host_authority_mapping.get(host, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)

tenant_id = "tenant_id"
client_id = "app_id"
client_secret = "secret"

host = input("Enter hostname: ")
print()

authority = get_authority_for_host(host)

credential = ClientSecretCredential(
    tenant_id=tenant_id,
    client_id=client_id, 
    client_secret=client_secret,
    authority=authority
)

access_token = credential.get_token("https://{host}/.default".format(host=host))
print(access_token.token)

Response:

enter image description here

When I decoded the above token in jwt.ms website, I got claims with aud as below:

enter image description here