Power BI - how to authenticate to app powerbi com silently

0 votes

I have tried the method outlined in the Microsoft docs

which involves creating an app in Active Directory and then having code something very similar to:

var authContextUrl = "https://login.windows.net/common/oauth2/authorize";
var authenticationContext = new AuthenticationContext(authContextUrl);
var redirectUri = "https://dev.powerbi.com/Apps/SignInRedirect";
var pp = new PlatformParameters(PromptBehavior.Auto);
var result = authenticationContext.AcquireTokenAsync(PowerBiApiResource, clientId, new Uri(redirectUri), pp).GetAwaiter().GetResult();

if (result == null)
{
    throw new InvalidOperationException("Failed to obtain the PowerBI API token");
}

var token = result.AccessToken;
return token;

I got this code working but it always insisted on prompting for a username and password, which is a problem for a function app.

I have also tried the approach in the silent function specified here

https://community.powerbi.com/t5/Developer/Data-Refresh-by-using-API-Need-Steps/m-p/209371#M6614

   static string getAccessTokenSilently()
    {

        HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp("https://login.windows.net/common/oauth2/token");
        //POST web request to create a datasource.
        request.KeepAlive = true;
        request.Method = "POST";
        request.ContentLength = 0;
        request.ContentType = "application/x-www-form-urlencoded";

        //Add token to the request header
        request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

        NameValueCollection parsedQueryString = HttpUtility.ParseQueryString(String.Empty);
        parsedQueryString.Add("client_id", clientID);
        parsedQueryString.Add("grant_type", "password");
        parsedQueryString.Add("resource", resourceUri);
        parsedQueryString.Add("username", username);
        parsedQueryString.Add("password", password);
        string postdata = parsedQueryString.ToString();


        //POST web request
        byte[] dataByteArray = System.Text.Encoding.ASCII.GetBytes(postdata); ;
        request.ContentLength = dataByteArray.Length;

        //Write JSON byte[] into a Stream
        using (Stream writer = request.GetRequestStream())
        {
            writer.Write(dataByteArray, 0, dataByteArray.Length);
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            dynamic responseJson = JsonConvert.DeserializeObject<dynamic>(responseString);
            return responseJson["access_token"];
        }


    }

This code doesn't work.

Also this has issues, although I haven't tried it:

https://docs.microsoft.com/en-us/power-bi/developer/get-azuread-access-token

There doesn't appear to be anything up to date available that works that explains how to do this. Does anyone know how?

Feb 21, 2022 in Power BI by surbhi
• 3,820 points
4,365 views

1 answer to this question.

0 votes

 I have to create the application in AD using https://dev.powerbi.com/apps and then login using a powerbi pro userid and password, using the following code:

public static string GetPowerBiAccessToken(string tenantId, string clientId, string userId, string password)
{
    var url = $"https://login.windows.net/{tenantId}/oauth2/token";

    var request = (HttpWebRequest)WebRequest.Create(url);
    request.KeepAlive = true;
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    var dataToPost = new Dictionary<string,string>
    {
        {"client_id", clientId},
        {"grant_type", "password"},
        {"resource", PowerBiApiResource},
        {"username", userId},
        {"password", password},
        {"redirect_uri", "https://dev.powerbi.com/Apps/SignInRedirect" }
    };

    var postData = string.Empty;
    foreach (var item in dataToPost)
    {
        if (!string.IsNullOrEmpty(postData))
            postData += "&";
        postData += $"{item.Key}={item.Value}";
    }

    var dataByteArray = System.Text.Encoding.ASCII.GetBytes(postData);
    request.ContentLength = dataByteArray.Length;

    using (var writer = request.GetRequestStream())
    {
        writer.Write(dataByteArray, 0, dataByteArray.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    var responseJson = JsonConvert.DeserializeObject<dynamic>(responseString);
    return responseJson["access_token"];
}

Are you ready to take your data visualization skills to the next level? Join our Power BI Training Course and learn how to transform your raw data into interactive and insightful reports!

answered Feb 21, 2022 by CoolCoder
• 4,420 points

Related Questions In Power BI

+1 vote
1 answer

Is it possible to manage limits while using dedicated capacity power bi embedded app service?

These limits are not related to using ...READ MORE

answered Sep 24, 2018 in Power BI by Hannah
• 18,520 points
705 views
0 votes
1 answer

How to assign Power BI license to a new user

The assign license method of MS Graph API might ...READ MORE

answered Sep 25, 2018 in Power BI by Kalgi
• 52,350 points
868 views
0 votes
1 answer

How to publish .pbix report from power bi desktop to power bi service directly?

To save powerbi file directly to report ...READ MORE

answered Sep 27, 2018 in Power BI by Kalgi
• 52,350 points
1,944 views
0 votes
1 answer

How to add an image to power bi report – power bi web

There are visuals (e.g. table) that can ...READ MORE

answered Sep 27, 2018 in Power BI by Kalgi
• 52,350 points
1,373 views
0 votes
1 answer

Displaying Table Schema using Power BI with Azure IoT Hub

Answering your first question, Event Hubs are ...READ MORE

answered Aug 1, 2018 in IoT (Internet of Things) by nirvana
• 3,130 points
1,311 views
+1 vote
1 answer

Unable to install connector for Power Bi and PostgreSQL

I think the problem is not at ...READ MORE

answered Aug 22, 2018 in Power BI by nirvana
• 3,130 points
2,722 views
+2 votes
2 answers

Migrate power bi collection to power bi embedded

I agree with Kalgi, this method is ...READ MORE

answered Oct 11, 2018 in Power BI by Hannah
• 18,520 points
1,492 views
+1 vote
1 answer

Connect power bi desktop to dataset and create custom reports

Yes using Power BI REST API to ...READ MORE

answered Sep 18, 2018 in Power BI by Kalgi
• 52,350 points
1,646 views
0 votes
1 answer

How to bind multiple Power BI datasets to a single Power BI Report

This is not an option. These are ...READ MORE

answered Feb 21, 2022 in Power BI by CoolCoder
• 4,420 points
2,280 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP