Try to set scope as {your-api-client-id}/.default to get access token. Replace your-api-client-id with the client id/application id for your API app in Azure AD.

Answer from unknown on Stack Overflow
🌐
Microsoft Learn
learn.microsoft.com › en-us › python › api › azure-identity › azure.identity.defaultazurecredential
azure.identity.DefaultAzureCredential class | Microsoft Learn
... Request an access token for scopes. This method is called automatically by Azure SDK clients. get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) -> AccessToken
🌐
Microsoft Learn
learn.microsoft.com › en-us › python › api › overview › azure › identity-readme
Azure Identity client library for Python | Microsoft Learn
As of version 1.14.0, DefaultAzureCredential attempts to authenticate with all developer credentials until one succeeds, regardless of any errors previous developer credentials experienced. For example, a developer credential may attempt to get a token and fail, so DefaultAzureCredential will continue to the next credential in the flow.
Discussions

Generate longer token for Databricks with Azure.
Is there a way to get a longer token for databricks with a Service Principal ? Since this aim to be for production, I wish my code could generate a PAT for any run, I don't want to create a PAT manually and store it to an Azure Key Vault. ... I made up an alternative solution. I made up my own python class to handle my PAT from Databricks : https://stackoverflow.com/questions/75071869/python-defaultazurecredential... More on community.databricks.com
🌐 community.databricks.com
2
1
January 16, 2023
python 3.x - How to properly use "get_token" of "ManagedIdentityCredential" of azure identity - Stack Overflow
I am trying to use managed identity of Azure function to access AAD protected web app, which requires a custom flow instead of using different clients. So the first step is to obtain an access token: More on stackoverflow.com
🌐 stackoverflow.com
DefaultAzureCredential doesn't authenticate successfully (even when logged in via CLI
But it took 2 minutes to acquire a token in this case, with a lot of exceptions. ... Thanks for the updates. This behavior is by design. DefaultAzureCredential is a chain of credentials and attempts the credentials in order. You can get more details at https://github.com/Azure/azure-sdk-for-python/... More on github.com
🌐 github.com
January 25, 2023
databricks - Python DefaultAzureCredential get_token set expiration or renew token - Stack Overflow
I'm using DefaultAzureCredential from azure-identity to connect to Azure with service principal environment variables (AZURE_CLIENT_SECRET, AZURE_TENANT_ID, AZURE_CLIENT_ID). I can get_token from a More on stackoverflow.com
🌐 stackoverflow.com
🌐
Microsoft Learn
learn.microsoft.com › en-us › python › api › azure-identity › azure.identity.aio.defaultazurecredential
azure.identity.aio.DefaultAzureCredential class | Microsoft Learn
... Asynchronously request an access token for scopes. This method is called automatically by Azure SDK clients. async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) -> AccessToken
🌐
Medium
medium.com › @oliverdevijt › why-defaultazurecredential-fails-after-az-login-tenant-and-how-to-fix-it-707ac747ace0
Why DefaultAzureCredential fails after az login --tenant (and how to fix it) | by Oliver De Vijt | Medium
April 16, 2025 - When working with Azure SDK for Python, you might use DefaultAzureCredential for a seamless authentication experience. However, a common frustration is seeing it fail to acquire a token even after you’ve run az login --tenant <tenant-id> to authenticate via the Azure CLI.
🌐
Databricks Community
community.databricks.com › databricks community › data engineering › generate longer token for databricks with azure.
Solved: Generate longer token for Databricks with Azure. - Databricks Community - 12614
January 16, 2023 - Every X minutes I ask for a new token, but I have to re init my sparksession and loose all the work. Isn"t a way to inject the token in spark.config ? ... I made up an alternative solution. I made up my own python class to handle my PAT from Databricks : https://stackoverflow.com/questions/75071869/python-defaultazurecredential-get-token-set-expiration-...
🌐
Microsoft Learn
learn.microsoft.com › en-us › azure › developer › python › sdk › authentication › credential-chains
Credential chains in the Azure Identity library for Python - Python on Azure | Microsoft Learn
January 15, 2026 - The AzureCliCredential.get_token call succeeds and the output also indicates that DefaultAzureCredential acquired a token from AzureCliCredential.
Find elsewhere
🌐
PyPI
pypi.org › project › azure-identity
azure-identity · PyPI
1 week ago - InteractiveBrowserCredential.g... on Python 2.7 (#14773) AzureCliCredential.get_token correctly sets token expiration time, preventing clients from using expired tokens (#14345) ... AzureCliCredential.get_token correctly sets token expiration time, preventing clients from using expired tokens (#14345) ... DefaultAzureCredential allows specifying ...
🌐
Medium
gabrielgomes61320.medium.com › microsoft-identity-library-deep-dive-e79c5d38109c
Microsoft Identity library Deep Dive | by Gabriel Gomes, PhD | Medium
December 18, 2023 - The default.py file contains the DefaultAzureCredential Class, with two methods inside it: the standard __init__ method (which is an instance method that initializes a newly created object), and the get_token method.
🌐
GitHub
github.com › Azure › azure-sdk-for-python › blob › main › sdk › identity › azure-identity › azure › identity › _credentials › default.py
azure-sdk-for-python/sdk/identity/azure-identity/azure/identity/_credentials/default.py at main · Azure/azure-sdk-for-python · GitHub
<"https://aka.ms/azsdk/python/identity/credential-chains#usage-guidance-for-defaultazurecredential">`__. · The identity it uses depends on the environment. When an access token is needed, it requests one using these · identities in turn, stopping when one provides a token: ·
🌐
OneUptime
oneuptime.com › home › blog › how to authenticate with azure services using azure-identity
How to Authenticate with Azure Services Using azure-identity
February 16, 2026 - On your development machine, DefaultAzureCredential typically uses your Azure CLI session. Make sure you are logged in first. # Log in to Azure CLI az login # Verify your account az account show · Once logged in, any Python script using DefaultAzureCredential will automatically use your CLI session.
🌐
Windows
azuresdkdocs.z19.web.core.windows.net › python › azure-identity › latest › azure.identity.html
azure.identity package — Azure SDK for Python 2.0.0 documentation
require_envvar (bool) – If True, require that the AZURE_TOKEN_CREDENTIALS environment variable be set to a value denoting the credential type or credential group to use. If unset or empty, DefaultAzureCredential will raise a ValueError. Defaults to False. ... Close the transport session of each credential in the chain. get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) → AccessToken[source]
🌐
GitHub
github.com › Azure › azure-sdk-for-python › issues › 28478
DefaultAzureCredential doesn't authenticate successfully (even when logged in via CLI · Issue #28478 · Azure/azure-sdk-for-python · GitHub
January 25, 2023 - But it took 2 minutes to acquire a token in this case, with a lot of exceptions. ... Thanks for the updates. This behavior is by design. DefaultAzureCredential is a chain of credentials and attempts the credentials in order. You can get more details at https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential.
Top answer
1 of 1
3

I guess there is no option to make this "host" token last longer. So I created a class to handle my PAT following databrick's 2.O API for tokens https://docs.databricks.com/dev-tools/api/latest/tokens.html

Thankfully PATs are automatically removed once they are expired. So I don't have to handle old PATs.

import json
from typing import Dict, List

import requests
from azure.identity import DefaultAzureCredential


class DatabricksTokenManager:
    """Databricks Token Manager. Based on https://docs.databricks.com/dev-tools/api/latest/index.html
    It uses `DefaultAzureCredential` to generate a short token for Databricks. Then it can manage Databricks PATs.
    """

    def __init__(self, databricks_host) -> None:
        """Init DatabricksTokenManager

        Args:
            databricks_host (str): Databricks host with out "https" or ending "/"
        """
        self._token = self._get_databricks_token()
        self.databricks_host = databricks_host
        self._pat = None

    @property
    def token(self) -> str:
        """Token property

        Returns:
            str: token value
        """
        return self._token

    @property
    def pat(self) -> str:
        """PAT property

        Returns:
            str: PAT value
        """
        return self._pat

    def _get_databricks_token(self) -> str:
        """Get auto generated token from Default Azure Credentials.
        If you are running this code in local. You need to run `az login`. Or set Service Principal Environment Variables.

        Returns:
            str: Databricks temporary Token
        """
        dbx_scope = "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"
        return DefaultAzureCredential().get_token(dbx_scope).token


    def list_databricks_pats(self) -> List[Dict]:
        """List all PATs for this user in Databricks

        Returns:
            list: List of dicts containing PAT info
        """
        headers = {
            "Authorization": f"Bearer {self.token}",
        }
        response = requests.get(
            f"https://{self.databricks_host}/api/2.0/token/list", headers=headers
        )
        return response.json()["token_infos"]

    def create_databricks_pat(self, comment=None) -> str:
        """Create and return a new PAT from Databricks

        Args:
            comment (str:Optional): Comment to link to PAT. Default None
        Returns:
            str: PAT value
        """
        if comment is None:
            comment = "Token created from datalab-framework"

        headers = {
            "Content-type": "application/json",
            "Authorization": f"Bearer {self.token}",
        }
        json_data = {
            "application_id": "ce3b7e02-a406-4afc-8123-3de02807e729",
            "comment": comment,
            "lifetime_seconds": 86400, # 24 Hours
        }
        response = requests.post(
            f"https://{self.databricks_host}/api/2.0/token/create",
            headers=headers,
            json=json_data,
        )
        self._pat = response.json()["token_value"]
        return self._pat

    def remove_databricks_pat(self, pat_id):
        """Remove PAT from databricks

        Args:
            pat_id str: PAT ID
        """
        headers = {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/x-www-form-urlencoded",
        }
        data = {"token_id": f"{pat_id}"}
        requests.post(
            f"https://{self.databricks_host}/api/2.0/token/delete",
            headers=headers,
            data=json.dumps(data),
        )
Top answer
1 of 2
8

Just to supplement the accepted answer with some more details, let me add that DefaultAzureCredential does log this information. For example, if you enable INFO-level logging:

import logging
from azure.identity import DefaultAzureCredential

logger = logging.getLogger('azure.identity')
logger.setLevel(logging.INFO)

handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('[%(levelname)s %(name)s] %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

You'll see log messages like these from DefaultAzureCredential:

[INFO] DefaultAzureCredential - EnvironmentCredential is unavailable
[INFO] DefaultAzureCredential - ManagedIdentityCredential is unavailable
[INFO] DefaultAzureCredential - SharedTokenCacheCredential is unavailable
[INFO] DefaultAzureCredential acquired a token from VisualStudioCodeCredential

You'll see the failed attempts logged only the first time the DefaultAzureCredential instance acquires a token. Once one of its constituent credentials provides a token, it uses that credential exclusively. So this particular DefaultAzureCredential will always authenticate through Visual Studio Code, and in the logs you'll see this message whenever it does so:

[INFO] DefaultAzureCredential acquired a token from VisualStudioCodeCredential
2 of 2
2

There are a few ways I might approach this but none are particularly pretty. At the risk of a naive suggestion, if you want a fine-grained understanding of what worked in sequence, you could take an approach similar to what your example sketched out using the components credentials listed here:

for credential in [EnvironmentCredential, ManagedIdentityCredential, ...]:
  try:
    credentials = credential()
    # Validate credential functionality...
    logging.info('{}.get_token succeeded'.format(credential))
  except Error1 as e1:
    logging.error('{} failed due to {}'.format(credential, e1))

I suggest this because it does not seem like what you want is exposed in an easily accessible manner, looking at the ChainedCredential source here (history is built up but only used in the log message).

More "self-contained" approaches might involve creating a custom wrapper that basically does what ChainedCredential does for DefaultAzureCredential in running the list of get_token calls, but with more ability to export the success history, you could likely hack that off of the code I linked in 2 and do something directly comparable to the DefaultAzureCredential logic, but at the end of the day it's all isomorphisms of the sample above.

Don't hesitate to shout if I've misunderstood some aspect of the question or your requirements/constraints; and as always feel free to reach out if you need to get in touch with us on our github (full disclosure, am a maintainer for some of the other Python Azure SDKs)

🌐
Microsoft Learn
learn.microsoft.com › en-us › python › api › azure-core › azure.core.credentials.tokencredential
azure.core.credentials.TokenCredential class | Microsoft Learn
Request an access token for scopes. get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) -> AccessToken
🌐
YouTube
youtube.com › watch
11. Azure using Python SDK : What is DefaultAzureCredentials and How to use it ? - YouTube
In this video, we will cover what is DefaultAzureCredentials ? What is the benefit of it and how to use it ?Chapters :************************************0:0...
Published: June 9, 2024
Top answer
1 of 3
6

When I use the .net Microsoft.IdentityModel.Clients.ActiveDirectory library I don’t have to think about scope.

Actually, you have thought about it. When you use the code below via .net sdk, there is an aasUrl, this is the equivalent you need to specify in python sdk.

AuthenticationResult authenticationResult = await authContext.AcquireTokenAsync(aasUrl, clientCred);

With Microsoft.IdentityModel.Clients.ActiveDirectory, the method AcquireTokenAsync essentially uses the Azure AD client credential flow v1.0 endpoint to get the token, so this parameter is named as resource, i.e. the resource parameter in this method AcquireTokenAsync(String, ClientCredential).

In python sdk azure.identity, this method get_token essentially uses Azure AD client credential flow v2.0 endpoint to get the token, when v1.0 endpoint migrates to v2.0, there are some changes, one of them is the resource, it changed to scope, see this doc. When using scope, you need to specify the permission you want to access, you can also use /.default, then by default all the permissions added to the app will be requested.

So in your case, you just need to use the scope as aasUrl/.default, e.g. https://management.azure.com/.default, it depends on yourself.

token = credential.get_token("https://management.azure.com/.default")

Also have a test with the code on my side, it works fine.

2 of 3
0

if you are using Graph API you could use as

https://graph.microsoft.com/.default

https://graph.microsoft.com/Directory.Read

https://graph.microsoft.com/user_impersonation

if you are using Azure Resource Manager API then the base uri would be https://management.core.windows.net followed by the necessary permission.

If you want to acquire a token for all the static scopes of a v1.0 application, append ".default" to the app ID URI of the API

You Will see the APP Id uri in the Application Overview page

if you have not created app id uri, you set the uri and add permission scope