2

I am trying to do the Dataset refresh for a PowerBI Report. I created the gateway and I am able to do the dataset refresh from the admin portal. I could validate that the refresh happend successfully from UI i.e. Last Refresh column in the Admin portal. But when I try to do the refresh from a C# webapi code, I am getting the below mentioned error.

Error Message:
The remote server returned an error: (401) Unauthorized.

Stack Trace:
   at System.Net.HttpWebRequest.GetResponse()
   at BlueSkyPowerBIService.Controllers.PowerBIController.<RefreshDatasetsForReports>d__13.MoveNext() in C:\Krishnan\RSI\SourceCode\Bluesky Developement\BlueSky Development\BlueSkyPowerBIService\BlueSkyPowerBIService\Controllers\PowerBIController.cs:line 258

Before the refresh code, I am able to do the authentication agains the Azure AD and it succeeds and generated the auth token, but when it call the API to refresh it crashes with the above said error.

Please find my code which i am use for data refresh

List<ReportDetails> reportDetailsList = new List<ReportDetails>();

            var result = new EmbedConfig();
            ReportDetails reportDetails = new ReportDetails();
            try
            {
                result = new EmbedConfig { Username = username, Roles = roles };
                var error = GetWebConfigErrors();
                if (error != null)
                {
                    result.ErrorMessage = error;
                    //return View(result);
                    return null;
                }
                var credential = new UserPasswordCredential(Username, Password);

                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

                if (authenticationResult == null)
                {
                    result.ErrorMessage = "Authentication Failed.";
                    //return View(result);
                    return null;
                }

                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
                {
                    // Get a list of reports.
                    var reports = await client.Reports.GetReportsAsync();
                    for (int index = 0; index < reports.Value.Count; index++)
                    {
                        reportDetails = new ReportDetails();
                        Report report = reports.Value[index];

                        HttpWebRequest request;

                        if (report.Id == "6317f207-57d3-4f5f-9644-18bfbb9bef99")
                        {
                            var url = "https://api.powerbi.com/v1.0/myorg/groups/{0}/datasets/{1}/refreshes";
                            request = System.Net.HttpWebRequest.CreateHttp(String.Format(url, GroupId, report.DatasetId));

                            request.KeepAlive = true;
                            request.Method = "POST";
                            request.ContentLength = 0;

                            request.Headers.Add("Authorization", String.Format("Bearer {0}", authenticationResult.AccessToken));

                            using (Stream writer = request.GetRequestStream())
                            {
                                var response = (HttpWebResponse)request.GetResponse();
                                Console.WriteLine("Dataset refresh request{0}", response.StatusCode.ToString());
                            }
                        }
                    }//end for(int index=0; index< reports.Value.Count; index++)
                    return reportDetailsList;
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault());
            }
            catch (Exception exc)
            {
                result.ErrorMessage = exc.ToString();
            }

I have granted all the required permissions in Azure portal under App Registrations, enter image description here

Any ideas why I am getting this error? How to fix this issue?

Krishnan
  • 958
  • 5
  • 21
  • 44

1 Answers1

0

This looks like a wrong configuration on the permissions of the Azure Active Directory application you are using to perform the refresh. As shown here we need to register a native app and declare some permissions to be able to access the Power BI rest API.

You need to make sure that this app has the Dataset.ReadWrite.All permission. You can see and even change permissions of the application in Azure portal under Azure Active Directory -> App Registrations. If you can't see the application select All apps from the drop down on the right.

This is how our application looks like that we are using successfully to perform a refresh through the rest API

enter image description here

xabikos
  • 195
  • 11
  • thanks for your reply, i am aware of this and I have already given all the permissions under "Power BI Service (Microsoft.Azure.AnalysisServices)" and "Windows Azure Active Directory". (Please refer the snapshot I have attached in my post) In-spite of this I am getting this error. Hence I have posted this issue, any thoughts why I am getting this error? – Krishnan Jun 06 '18 at 14:33
  • @Krishnan I think the app registration has not granted permissions to the right API. I updated the screenshot on my answer. As you can see in our case the API says only _Power BI Service_ and in the enable access says again _Power BI service_. In the one you posted it mentions _Analysis Services_. Could you give it a try? – xabikos Jun 06 '18 at 22:08
  • 1
    im getting the same issue. Did you ever resolve this? thanks – resolver101 Feb 15 '19 at 14:53
  • Please refer my post in the link https://stackoverflow.com/a/51228559/6167659 I have written an article of how to configure the permissions and steps for dataset refresh.. – Krishnan Apr 30 '19 at 19:59