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

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...