pythonazureauthenticationaccess-tokenazure-authentication

Device Code Flow - Microsoft Azure Authentication


What is the duration of the token we get when authenticating to Azure resources using Device Code Flow: https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-acquire-token-device-code-flow?tabs=dotnet.

Is there a "refresh token" that we can activate after the first one expires? If so, is the refresh token activated behind the scenes, or should I manually activate it (and how)?


Solution

  • I created an Azure AD Application and enabled the mobile and desktop flows:

    enter image description here

    I used the below Python code to generate the access token to authenticate Microsoft Graph API for sample:

    import msal
    
    config = {
        "client_id": "ClientID",
        "authority": "https://login.microsoftonline.com/TenantID",
        "scope": ["User.Read"],
    }
    app = msal.PublicClientApplication(
        config["client_id"], authority=config["authority"],
        token_cache=msal.SerializableTokenCache(),
    )
    
    result = None
    
    # First, try to get a token from the cache.
    accounts = app.get_accounts()
    if accounts:
        # Use the first account to acquire a token silently.
        result = app.acquire_token_silent(config["scope"], account=accounts[0])
    
    if not result:
        # If a token is not available in the cache, use the device flow to acquire a new token.
        flow = app.initiate_device_flow(scopes=config["scope"])
        print(flow["message"])
        result = app.acquire_token_by_device_flow(flow)
    
    # Use the access token to call the Microsoft Graph API.
    if "access_token" in result:
        access_token = result["access_token"]
        print(access_token)
    else:
        error = result.get("error")
        if error == "invalid_client":
            print("Invalid client ID.Please check your Azure AD application configuration")
        else:
            print(error)
    

    enter image description here

    And is there a "refresh token" that we can activate after the "initial token" reaches expiration? If so, is the refresh token activated behind the scenes, or should I explicitly activate it in the code?

    Note that: Azure AD MSAL refreshes the token automatically when the access token is about to expire. Refer this MsDoc.

    #check the cache to see whether we already have some accounts that the end user already used to sign in before.
    accounts = app.get_accounts()
    if accounts:
        # If so, you could then somehow display these accounts and let end user choose
        print("Pick the account you want to use to proceed:")
        for a in accounts:
            print(a["username"])
        # Assuming the end user chose this one
        chosen = accounts[0]
        # Now let's try to find a token in cache for this account
        result = app.acquire_token_silent(["User.Read"], account=chosen)
    

    References:

    Microsoft Authentication Library (MSAL) for Python

    MSAL Python 1.23.0 documentation (msal-python.readthedocs.io)