Azure Authentication using Python MSAL

Microsoft has released MSAL for Python. This has helped to shield away complexities in calling the API using urllib3 libraries and meddling with the parameters. In this article, I will provide sample code on how to get the access token using the following credentials type:

  • UserID and Password
  • Client ID and Client Secret

User ID and Password

To use user id and password similar to the grant type “password” in graph API, use the following code:

def authenticate():

  authority_host_url = 'https://login.microsoftonline.com'
  tenant = '<Your Tenant ID>'
  authority_url = authority_host_url + '/' + tenant
  client_id = '<Your Client ID>'

  username = '<User ID>'
  password = '<Password>'

  resource_url = '<Scope URL>'

  context = msal.PublicClientApplication(client_id, authority=authority_url)
  response = context.acquire_token_by_username_password(username, password, scopes=[resource_url])

  access_token = response['access_token']

  return access_token

You will need to provide the following:

  • Tenant ID
  • Client ID, this should be the application ID that you have created
  • User ID
  • Password
  • Scope URL will typically ends with /.default

Client ID and Client Secret

To use Client ID and Client Secret similar to the grant type “client_credentials” in graph API, use the following code:

def authenticate():

  authority_host_url = 'https://login.microsoftonline.com'
  tenant = '<Your Tenant ID>'
  authority_url = authority_host_url + '/' + tenant
  client_id = '<Your Client ID>'
  client_secret = '<Your Client Secret>'

  resource_url = '<Scope URL>'

  context = msal.ConfidentialClientApplication(client_id, authority=authority_url, client_credential=client_secret)
  response = context.acquire_token_silent(scopes=[resource_url], account=None)
  
  if not response:
    response = context.acquire_token_for_client(scopes=[resource_url])

  access_token = response['access_token']

  return access_token

You will need to provide the following:

  • Tenant ID
  • Client ID, this should be the application ID that you have created
  • Client Secret
  • Scope URL will typically ends with /.default

Leave a Comment