Showing results for 
Search instead for 
Did you mean: 
Thiasus Frequent Visitor
Frequent Visitor

[Python] Get AccessToken POST Request + Multi-factor Auth



I'm trying to get an AccessToken from but I have two problems


  • My user for security reason have MFA enabled, and cannot be disabled.
  • The code I have found doesn't work only using clientID and ClientSecret (Source)

The code below generates an access code, but the POST request retrieves 401 status code.


I can disable MFA and enter User and Password and would generate a valid access token, but that generates a massive security problem, besides implies that I would need to have a "permanent" account that would only have access to PBI for doing refreshes - basically a flaw into the system of APIs.


import adal
import requests
from msrestazure.azure_active_directory import AADTokenCredentials

authority_host_uri = ''
tenant = 'tenant'
authority_uri = authority_host_uri + '/' + tenant
resource_uri = ''
client_id = 'clientid'
client_secret = 'clientsecret'
context = adal.AuthenticationContext(authority_uri, api_version=None)
mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)
credentials = AADTokenCredentials(mgmt_token, client_id)

headers = {'Authorization': 'Bearer ' + mgmt_token['accessToken'], 'Content-Type': 'application/json'}
url = ''

r=, headers=headers)