Reputation: 1008
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,
Any ideas why I am getting this error? How to fix this issue?
Upvotes: 2
Views: 4212
Reputation: 195
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
Upvotes: 0