Search code examples
python-3.xactive-directoryazure-ad-msal

Unable to call PublicClientApplication.initiate_auth_code_flow() function


Background: I'm a relatively amateur programmer in general, so I may be barking up the wrong tree here. My AD organization requires MFA, so the simple PublicClientApplication.acquire_token_by_username_password() function does not suffice.

A snippet of my code is attached below (I am loading arguments from a json config file):

import json
import logging
import requests
import msal


# Optional logging
# logging.basicConfig(level=logging.DEBUG)  # Enable DEBUG log for entire script
# logging.getLogger("msal").setLevel(logging.INFO)  # Optionally disable MSAL DEBUG logs

with open("config.json", "r") as jsonfile:
    config = json.load(jsonfile)
    print("Read successful")
    # Create a preferably long-lived app instance which maintains a token cache.
    app = msal.PublicClientApplication(
        config["client_id"], authority=config["authority"],
        client_credential=config.get("client_secret"),
        # token_cache=...  # Default cache is in memory only.
                           # You can learn how to use SerializableTokenCache from
                           # https://msal-python.readthedocs.io/en/latest/#msal.SerializableTokenCache
        )
    
    
    # The pattern to acquire a token looks like this.
    result = None
    
    # Skipping error condition
    
    # Firstly, check the cache to see if this end user has signed in before
    accounts = app.get_accounts(username=config["username"])
    if accounts:
        logging.info("Account(s) exists in cache, probably with token too. Let's try.")
        result = app.acquire_token_silent(config["scope"], account=accounts[0])
    
    if not result:
        logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
        #initiate authorization code flow
        flow = app.initiate_auth_code_flow(config["scope"])
        #check if token is good
        result = app.acquire_token_by_authorization_code(flow, config["scope"])
    
            

When trying to call:

app.initiate_auth_code_flow(config["scope"])

I receive the error:

'PublicClientApplication' object has no attribute 'initiate_auth_code_flow'

I know that initiate_auth_code_flow() is certainly part of the msallib, and within the PublicClientApplication Class, so I'm at a loss here.


Solution

  • I originally installed msal using the conda command:

    conda install -c conda-forge/label/cf202003 msal
    

    Reinstalling msal using the following conda command fixed my issue:

    conda install -c conda-forge msal