Forum Discussion

cdout's avatar
cdout
Frequent Visitor
4 years ago

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