Overview
In this article, we will talk about how we can create an Azure Function APP to generate tokens.
Before we start I prefer you read my earlier articles,
- Overview of Power BI Embedded
- Register the Power BI Application in Azure AD
- Common steps to Embed Power BI report to the third party application
Now, let’s get started!
Create an Azure App Function
- Open Azure Portal.
- Go to All Resources > Add > Serverless Function App.

- Give a name for your App function.
Here, my application name = PBIReportEmbedded
Click on the Create button.

- Now, from the left navigation,> Click on Function Apps > Click on PBIReportEmbedded which we have created in Step 3.

- Click on Application Setting.

- We need to add the following Key-value Pairs.
PBIE_CLIENT_ID = Application ID for the Application we have registered. PBIE_GROUP_ID = Workspace ID of Power BI Report. PBIE_REPORT_ID = Report ID of Power BI Report. PBIE_USERNAME = Username of Power BI Pro account PBIE_PASSWORD = Password of Power BI Pro account
- From Functions > Click on + icon > Select Webhook + API > CSharp > Create this function.

- Click on View Files

- Add a file named “project.json”.

- Add the following code snippet to the “project.json” file.
{ "frameworks": { "net46": { "dependencies": { "Microsoft.IdentityModel.Clients.ActiveDirectory": "3.19.4", "Microsoft.PowerBI.Api": "2.0.12" } } } } - Open the “run.csx” file.

- Add the following code snippet.
#r "System.Web.Extensions" using System.Configuration; using System.Net; using System.Text; using System.Web.Script.Serialization; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.PowerBI.Api.V2; using Microsoft.PowerBI.Api.V2.Models; using Microsoft.Rest; // Static Values static string authorityUrl = "https://login.windows.net/common/oauth2/authorize/"; static string resourceUrl = "https://analysis.windows.net/powerbi/api"; static string apiUrl = "https://api.powerbi.com/"; static string clientId = ConfigurationManager.AppSettings["PBIE_CLIENT_ID"]; 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; } } - Run the code. You will get the following output.

- If you get an error like “500: Internal Server” then make sure you have applied “Grant Permission” in Azure Portal like the following image.

- Your Azure App function is ready to use.
In my next article, we will check how we can embed a Power BI report in an HTML page using the Azure App function.
Conclusion
This is how we can create Azure APP Function. Hope you love this article. Stay connected with me!

Hassan IftikharPosted Mar 11, 2022, 10:46 AM
Hi - Is there any way to get Power BI access token without registering application on Azure AD, in order to display Power BI reports to any external web application?
Arkadyuti RoyChoudhuryPosted Dec 12, 2019, 6:10 AM
Hi Dhruvin,Need your help in Embed Token in azure.I have earlier created embedded token using your code in project.json and run.csx. But now when I am using the same code it is giving error stating 2019-12-12T11:57:59.220 [Error] Exception while executing function: Functions.HttpTriggerCSharp1. Microsoft.Azure.WebJobs.Script: One or more errors occurred. Microsoft.IdentityModel.Clients.ActiveDirectory: parsing_wstrust_response_failed: Parsing WS-Trust response failed. 2019-12-12T11:57:59.267 [Error] Function completed (Failure, Id=9efad37e-f7f9-473e-a36d-19be8591f5a1, Duration=1702ms)
chetan khanapurePosted Jul 15, 2019, 9:15 AM
I tried this, it's working on Azure Portal and Generates Power bI Embedded Report on HTML. But now I created this same function in Visual Studio community 2019 was I am getting error's having no support of namespace System.Web.Script.Serialization;
Wayne DPosted Mar 2, 2019, 12:25 PM
Timestamp: 2019-02-22 18:35:24Z. Response status code does not indicate success: 400 (BadRequest). {"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID '8xxxxx04a2-xxxx-4fa7-b862-xxxxxxxxxxxxxxx'
Wayne DPosted Mar 2, 2019, 12:24 PM
Hello, we have followed these steps and everything works great using my ID, we have since added a new user but get the following error when we use the new ID/PW, do we need to grant permissions again in Azure to get this working using the new user ID/PW?
Daksh AgarwalPosted Dec 17, 2018, 2:54 AM
Hi Dhruvin , Instead of Azure Ad Client Id or Application Id is that okay if I would put PowerBI Application Or Client Id that we have created in previous step.
Richiearora 2001Posted Dec 10, 2018, 11:39 AM
I have a question- So i have a Test Power Bi Environment just a Sandbox - I am trying for Power BI embedded by User Owns Data Method. in the Power BI Playground . will i be able to pass Embedded token generated from Postman and my Power BI Group ID and Report ID? and Generate the code? and test if my report is accessible?
alain pilonPosted Nov 5, 2018, 12:22 PM
What prevents anyone from calling this function and get your token?