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(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

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.51 EF 6.0.2 VS2013 It see