Skip to main content

How to access Power BI resources from client application (first and third party embedding)

In this post, we will talk about different ways on how we can authenticate and authorize our applications to access our Power BI Reports. Things become a little bit confusing because there are reports that can be owned by the users that access them or by another user. Additional to this there are cases when the users own the report, but not the data that are displayed.
Before jumping to the solution, we need to understand a few concepts related to how Power BI works when you use embedded functionality. The basic idea of Power BI embedded functionality is the ability to integrate an IFRAME inside your application. Inside the IFRAME we can display any content we want from reports to dashboards.
The IFRAME content is loaded directly from Power BI services using an URL and a security token. The security token can be obtained from Azure AD thought your application.
This involves two steps for authentication. The first step is happening when you call directly or indirectly the Azure AD to obtain an access token to access Power BI. The second step is done using the access token that it is used by your application to call the Power BI and load the IFRAME. Inside the IFRAME the Power BI can load all requested content, including controllers.

First-Party Embedding
The access mechanism presented above is called First-Party Embedding. The access to content it’s smooth and is customized for each user. Each user that access the Power BI has a Power BI ‘account’ where you can manage what the user is able to do. Even so, each user needs to be a Power BI user and owns the data model (user-owns-data model). It is a great solution for applications and reports used internally inside an organization.
Anonymous access is not supported using this approach.

Third-Party Embedding
For cases when you need to provide access to your reports or Power BI resources to users that are not part of your organization or anonymous users, the approach needs to be a little different. You will not need to authenticate each user in front of AD and get obtain the security token.
In this scenario, you will need to authenticate to Power BI to obtain an embedded token. The embedded token can be used to access resources from Power BI, but keep in mind that each embedded token is generated for every single resource. It means that if you want to display two different reports, you will need to obtain two embedded tokens from Power BI.
This is possible using master accounts, that is allowing us to get the embedded token directly from Power BI. The problem with master accounts is the way how it works. They are offering access to a wide number of resources and data inside Power BI. Because of this people tends to create multiple master accounts, for each user type. This approach is not only non-scalable but it’s hard to manage and control.
The recommended solution is to use the roles that the user has and add them to the embedded token inside the EffectiveIdentity field. Using this information, the roles based on access to different data sets will work the same as it works for First-Party Embedding.

Samples
At this step, we have a base understating related to how Power BI works when we want to use embedding functionality. Let’s take a look at some samples related to how we should to the authentication and authorization.
Code source: this

(1) Third-Party Embedding without user interaction (console app)
The first step is to provide access to the master user account from the Azure AD Application.

...
  private static string aadAuthorizationEndpoint = "https://login.microsoftonline.com/common";
  private static string resourceUriPowerBi = "https://analysis.windows.net/powerbi/api";
  
  private static string applicationId = ConfigurationManager.AppSettings["application-id"];
  private static string userName = ConfigurationManager.AppSettings["aad-account-name"];
  private static string userPassword = ConfigurationManager.AppSettings["aad-account-password"];

  private static string GetAccessToken() {

    AuthenticationContext authenticationContext = new AuthenticationContext(aadAuthorizationEndpoint);

    AuthenticationResult userAuthnResult =
      authenticationContext.AcquireTokenAsync(
        resourceUriPowerBi,
        applicationId,
        new UserPasswordCredential(userName, userPassword)).Result;

    return userAuthnResult.AccessToken;
  }
...

(2) Third-Party Embedding inside a web app where user already auth
The below sample adds to the embedded token the user roles. This information can be used later to restrict content accessed by a specific user.

  string currentUserName = HttpContext.Current.User.Identity.GetUserName();
  ApplicationDbContext context = new ApplicationDbContext();
  var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
  ApplicationUser currentUser = userManager.FindByName(currentUserName);

  var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

  List<string> roles = new List<string>();

  foreach (var role in currentUser.Roles) {
    roles.Add(roleManager.FindById(role.RoleId).Name);
  }

  string accessLevel = HttpContext.Current.User.IsInRole("Admin") ? "edit" : "view";

  PowerBIClient pbiClient = GetPowerBiClient();

  var report = await pbiClient.Reports.GetReportInGroupAsync(workspaceId, reportId);
  var embedUrl = report.EmbedUrl;
  var reportName = report.Name;
  var datasetId = report.DatasetId;

  GenerateTokenRequest generateTokenRequestParameters =
    new GenerateTokenRequest(accessLevel: accessLevel,
                            identities: new List<EffectiveIdentity> {
                              new EffectiveIdentity(username: currentUser.UserName,
                                                    datasets: new List<string> { datasetId  },
                                                    roles: roles)
                            });

  string embedToken =
        (await pbiClient.Reports.GenerateTokenInGroupAsync(workspaceId,
                                                            report.Id,
                                                            generateTokenRequestParameters)).Token;

  return new ReportEmbeddingData {
    reportId = reportId,
    reportName = reportName,
    embedUrl = embedUrl,
    accessToken = embedToken
  };

(3) First-Party Embedding
Source: https://github.com/Microsoft/PowerBI-Developer-Samples/blob/master/User%20Owns%20Data/integrate-report-web-app/PBIWebApp/Default.aspx.cs

Comments

Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…