Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Join us for an expert-led overview of the tools and concepts you'll need to become a Certified Power BI Data Analyst and pass exam PL-300. Register now.

Reply
cdout
Frequent Visitor

Power BI Embed - get embed token with Azure Functions

I have a Power BI Embed application through an AD Azure registration on an "embed for your customers" method with a service principal.

 

I have been following this Taygan tutorial to embed power bi into my applications using Azure Functions. Link to the blog - https://www.taygan.co/blog/2018/05/14/embedded-analytics-with-power-bi

 

I need help passing the service principal instead of the username and password authentication, see lines in this section below:

   // Authenticate with Azure Ad > Get Access Token > Get Token Credentials

    var credential = new UserPasswordCredential(username, password);

    var authenticationContext = new AuthenticationContext(authorityUrl);

    var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);

    string accessToken = authenticationResult.AccessToken;

   

This blog is four years old so the code may need updating in general. Any thoughts on updating it are very welcome. 

 

Thanks, C.

 

 

 

#r "Newtonsoft.Json"

using System.Configuration;

using System.Net;

using System.Text;

using System.Web.Script.Serialization;

using Microsoft.IdentityModel.Clients;

using Microsoft.PowerBI.Api.V2;

using Microsoft.PowerBI.Api.V2.Models;

using Microsoft.Rest;

//added MS declarations here

using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Primitives;

using Newtonsoft.Json;





// Static Values



//Comment out Taygan's authorityURL for the new one

//static string authorityUrl = "https://login.windows.net/common/oauth2/authorize/";

static string authorityUrl: "https://login.microsoftonline.com/organizations/",

//Add authentication mode of "Service Principal" reference back to the Function App settings

Static string authenticationmode = ConfigurationManager.AppSettings["PBIE_AUTHENTICATION_MODE"]

static string resourceUrl = "https://analysis.windows.net/powerbi/api";

static string apiUrl = "https://api.powerbi.com/";

static string clientId = ConfigurationManager.AppSettings["PBIE_CLIENT_ID"];

//Added for client secret

Static string clientsecret =  ConfigurationManager.AppSettings["PBIE_CLIENT_SECRET"];

//Comment out Taygan's username and password auth

//static string username = ConfigurationManager.AppSettings["PBIE_USERNAME"];

//static string password = ConfigurationManager.AppSettings["PBIE_PASSWORD"];

static string groupId = ConfigurationManager.AppSettings["PBIE_GROUP_ID"];

static string reportId = ConfigurationManager.AppSettings["PBIE_REPORT_ID"];



public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)

{



    // Authenticate with Azure Ad > Get Access Token > Get Token Credentials

    var credential = new UserPasswordCredential(username, password);

    var authenticationContext = new AuthenticationContext(authorityUrl);

    var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);

    string accessToken = authenticationResult.AccessToken;

    var tokenCredentials = new TokenCredentials(accessToken, "Bearer");

   

    using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))

    {

        // Embed URL

        Report report = client.Reports.GetReportInGroup(groupId, reportId);

        string embedUrl = report.EmbedUrl;



        // Embed Token

        var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");

        EmbedToken embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, generateTokenRequestParameters);



        // JSON Response

        EmbedContent data = new EmbedContent();

        data.EmbedToken = embedToken.Token;

        data.EmbedUrl = embedUrl;

        data.ReportId = reportId;

        JavaScriptSerializer js = new JavaScriptSerializer();

        string jsonp = "callback(" +  js.Serialize(data) + ");";



        // Return Response

        return new HttpResponseMessage(HttpStatusCode.OK)

        {

            Content = new StringContent(jsonp, Encoding.UTF8, "application/json")

        };

    }

}



public class EmbedContent

{

    public string EmbedToken { get; set; }

    public string EmbedUrl { get; set; }

    public string ReportId { get; set; }

}

 

 

 

3 REPLIES 3
cdout
Frequent Visitor

Hello yingyinr and thank you for the reply. This above links aren't working for me because they use the method of embedding through a coded application loaded to the client website. I tried that and it works in a local host. 

 

I am looking for details using the method of an Azure Function App to run all of the code because my client doesn't allow a .net or vs code or other project to be loaded. The client only allows a one-page HTML and/or JS script. 

 

I'm looking for a methodology where the bulk of the work of getting the embed token and calling the api is done outside of the client, such as the az function app. Any thoughts? 

 

Regards, cdout

 

 

Hi, I am in the same situation. Did you get around the solution for this one? Thanks in advance!"

Helpful resources

Announcements
Join our Fabric User Panel

Join our Fabric User Panel

This is your chance to engage directly with the engineering team behind Fabric and Power BI. Share your experiences and shape the future.

June 2025 Power BI Update Carousel

Power BI Monthly Update - June 2025

Check out the June 2025 Power BI update to learn about new features.

June 2025 community update carousel

Fabric Community Update - June 2025

Find out what's new and trending in the Fabric community.

Top Solution Authors