Search code examples
c#azurepowerbiazure-functionsbearer-token

Power BI API from Azure Function C# Login Credential Help Bearer Token


I am trying to write an azure function that will call a paginated report from me from a power bi workspace. The issue that I'm having is that the credentials need to be a bearer token that Power Bi accepts. How would I go about getting this bearer token? Whether that be from power bi or 3rd party as long as it allows me to connect to power bi and grab my report

        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var credentials = new BasicAuthenticationCredentials();
            credentials.UserName = "[email protected]";
            credentials.Password = "password!";
            var PowerBIClient = new PowerBIClient(credentials);
            Guid groupId = new Guid("6xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx5");
            Guid reportId = new Guid("dxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx3");
            int pollingTimeOutInMinutes = 10;

            var file = await ExportPaginatedReport(reportId, groupId, pollingTimeOutInMinutes, PowerBIClient);


            return new OkObjectResult(file);

Solution

  • I was able to get the bearer token by using an azure enterprise application. I then added that application to a security group in AzureAd and added that security group to the admin portal in power bi that allows service principals to access your workspaces. (tenant_secrets is really just the tenant ID just need another name for it.)

          public static string GetAccessTokenWithLocalCredential(string client_id, string client_secret, string tenant_id)
            {
                string appId = client_id;
                string client_secrets = client_secret;
                string tenant_secrets = tenant_id;
                string tenantSpeceficAuthority = "https://login.microsoftonline.com/" + tenant_secrets;
                var appConfidential = ConfidentialClientApplicationBuilder.Create(appId)
                    .WithClientSecret(client_secret)
                    .WithAuthority(tenantSpeceficAuthority)
                    .Build();
                string[] scopes = { "https://analysis.windows.net/powerbi/api/.default" };
                var authResult = appConfidential.AcquireTokenForClient(scopes).ExecuteAsync().Result;
                return authResult.AccessToken;
    
            }