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

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

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!"

v-yiruan-msft
Community Support
Community Support

Hi  @cdout ,

You can refer the following links to get it:

Embedded analytics application tokens

 

Tutorial: Embed Power BI content using a sample embed for your customers' application

Embed Power BI content with service principal and an application secret

 

Embed Power BI Report for Customers using App Own Concept and Service Principal


Authenticate-ServicePrincipal/Embed for your customersyingyinr_0-1660638114307.png

Best Regards

Community Support Team _ Rena
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

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