How to generate Access Token for Azure with grant type password? PowerBI REST API

747 Views Asked by At

I want to be able to get access tokens automatically without the need of user interaction (that is manually typing the credentials in an OAuth pop-out). I'm using grant_type: password for this; however, I'm getting an invalid_grant error, saying the credentials are wrong but the credentials are correct since I can use them to login to the Azure platform.

I used Postman for this, with the tenant, client_id, and basic scopes shown in the Azure platform. POST: https://login.microsoftonline.com/{{tenant}}/oauth2/v2.0/token Content-Type: application/x-www-form-urlencoded Body:

client_id={{client_id}}
&client_secret={{client_secret}}
&scope=User.Read
&grant_type=password
&username={{[email protected]}}
&password={{password}}

Do you have any ideas as to what could be causing this error?

1

There are 1 best solutions below

0
On

The error usually occurs if you are using external user credentials in ROPC flow to generate access token.

As mentioned in this MS Documentation,

The Microsoft identity platform only supports the ROPC grant within Azure AD tenants, not personal accounts. Personal accounts that are invited to an Azure AD tenant can't use the ROPC flow.

I registered one Azure AD application and added User.Read API permission as below:

enter image description here

When I tried to generate access token using ROPC flow by including external user credentials, I got same error as you like below:

POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id: <appID> 
client_secret:<secret>
scope:User.Read
grant_type:password
username:demouser_gmail.com#EXT#@xxxxxxxxxx.onmicrosoft.com
password:xxxxxxxxx

Response:

enter image description here

To resolve the error, you need to change username and password with local Azure AD user credentials like below:

POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id: <appID> 
client_secret:<secret>
scope:User.Read
grant_type:password
username:[email protected]
password:xxxxxxxxx

Response:

enter image description here

But the above token won't work to call Power Bi as User.Read is Microsoft Graph permission. You need to add Power Bi permissions in your application to call Power Bi REST API like below:

enter image description here

While generating access token, make sure to change scope to https://analysis.windows.net/powerbi/api/.default like this:

POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id: <appID> 
client_secret:<secret>
scope: https://analysis.windows.net/powerbi/api/.default
grant_type:password
username:[email protected]
password:xxxxxxxxx

Response:

enter image description here

You can verify it by decoding the token in jwt.ms that have aud and scp claims as below:

enter image description here