Get access token on Microsoft federated accounts

Viewed 624

I'm trying to get access token for Power BI API. Our account is a federated account.

I've been trying this but it keeps giving me an error saying Incorrect username or password. To use the resource owner password credentials grant flow to get the access token for Azure AD, I make a call to http request diectly using the HttpClient

HttpClient clie = new HttpClient();
string tokenEndpoint = "https://login.microsoftonline.com/{tenant}/oauth2/token";
var body = "resource=https://analysis.windows.net/powerbi/api&client_id={client_id}&grant_type=password&username={username}&password={password}";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
string result = clie.PostAsync(tokenEndpoint, stringContent).ContinueWith((response) =>
            {
                return response.Result.Content.ReadAsStringAsync().Result;
            }).Result;

This will work for non federated accounts. How can I implement the same for federated accounts?

1 Answers

The easier would be to leverage MSAL.NET (or ADAL.NET) which does a lot to achieve that. See https://aka.ms/msal-net-up

scopes = new string[]{ "https://analysis.windows.net/powerbi/api/Dashboard.Read.All"}
result = await app.AcquireTokenByUsernamePasswordAsync(scopes, "joe@contoso.com",
                                                       securePassword);

Even better if you know that your machine is domain joined or AAD joined, you can use Integrated Windows Authentication: https://aka.ms/msal-net-iwa

result = await app.AcquireTokenByIntegratedWindowsAuthAsync(scopes);

Note that, I recommend using MSAL.NET (instead of ADAM.NET), because with MSAL/NET/the Azure AD v2.0 endpoint, PowerBI offers a better control of the permission scopes: enter image description here

See the API permissions tab in an app registration in https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview

Related