Create An Azure Function App To Generate Token - Power BI Embedded - Step By Step - Part Four

In this article, we will talk about how we can create an Azure Function APP to generate tokens.

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,

Now, let’s get started!

Create an Azure App Function

  1. Open Azure Portal.
  2. Go to All Resources > Add > Serverless Function App.


  3. Give a name for your App function.

    Here, my application name = PBIReportEmbedded

    Click on Create button.


  4. Now, from left navigation,> Click on Function Apps > Click on PBIReportEmbedded which we have created in Step3.


  5. Click on Application Setting.


  6. We need to add the following Key-value Pairs,

    1. PBIE_CLIENT_ID = Application ID for the Application we have registered.
    2. PBIE_GROUP_ID = Workspace ID of Power BI Report.
    3. PBIE_REPORT_ID = Report ID of Power BI Report.
    4. PBIE_USERNAME = Username of Power BI Pro account
    5. PBIE_PASSWORD = Password of Power BI Pro account


  7. From Functions > Click on + icon > Select Webhook + API > CSharp > Create this function.


  8. Click on View Files


  9. Add a file named “project.json”.


  10. Add the following code snippet to “project.json” file.
  1. {  
  2.   "frameworks": {  
  3.     "net46":{  
  4.       "dependencies": {  
  5.         "Microsoft.IdentityModel.Clients.ActiveDirectory""3.19.4",  
  6.         "Microsoft.PowerBI.Api""2.0.12"  
  7.       }  
  8.     }  
  9.    }  
  10. }  

11. Open “run.csx” file.

 

12. Add the following code snippet.

  1. #r "System.Web.Extensions"  
  2. using System.Configuration;  
  3. using System.Net;  
  4. using System.Text;  
  5. using System.Web.Script.Serialization;  
  6. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  7. using Microsoft.PowerBI.Api.V2;  
  8. using Microsoft.PowerBI.Api.V2.Models;  
  9. using Microsoft.Rest;  
  10.   
  11. // Static Values  
  12. static string authorityUrl = "https://login.windows.net/common/oauth2/authorize/";  
  13. static string resourceUrl = "https://analysis.windows.net/powerbi/api";  
  14. static string apiUrl = "https://api.powerbi.com/";  
  15. static string clientId = ConfigurationManager.AppSettings["PBIE_CLIENT_ID"];  
  16. static string username = ConfigurationManager.AppSettings["PBIE_USERNAME"];  
  17. static string password = ConfigurationManager.AppSettings["PBIE_PASSWORD"];  
  18. static string groupId = ConfigurationManager.AppSettings["PBIE_GROUP_ID"];  
  19. static string reportId = ConfigurationManager.AppSettings["PBIE_REPORT_ID"];  
  20.   
  21. public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)  
  22. {  
  23.   
  24.     // Authenticate with Azure Ad > Get Access Token > Get Token Credentials  
  25.     var credential = new UserPasswordCredential(username, password);  
  26.     var authenticationContext = new AuthenticationContext(authorityUrl);  
  27.     var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);  
  28.     string accessToken = authenticationResult.AccessToken;  
  29.     var tokenCredentials = new TokenCredentials(accessToken, "Bearer");  
  30.       
  31.     using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))  
  32.     {  
  33.         // Embed URL  
  34.         Report report = client.Reports.GetReportInGroup(groupId, reportId);  
  35.         string embedUrl = report.EmbedUrl;  
  36.   
  37.         // Embed Token  
  38.         var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");  
  39.         EmbedToken embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, generateTokenRequestParameters);  
  40.   
  41.         // JSON Response  
  42.         EmbedContent data = new EmbedContent();  
  43.         data.EmbedToken = embedToken.Token;  
  44.         data.EmbedUrl = embedUrl;  
  45.         data.ReportId = reportId;  
  46.         JavaScriptSerializer js = new JavaScriptSerializer();  
  47.         string jsonp = "callback(" +  js.Serialize(data) + ");";  
  48.   
  49.         // Return Response  
  50.         return new HttpResponseMessage(HttpStatusCode.OK)   
  51.         {  
  52.             Content = new StringContent(jsonp, Encoding.UTF8, "application/json")  
  53.         };  
  54.     }  
  55. }  
  56.   
  57. public class EmbedContent  
  58. {  
  59.     public string EmbedToken { getset; }  
  60.     public string EmbedUrl { getset; }  
  61.     public string ReportId { getset; }  
  62. }  

13. Run the code.You will get the following output.

 

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

 

15. Your Azure App function is ready to use.

In my next article, we will check how we can embed Power BI report in an HTML page using Azure App function

Conclusion

This is how we can create Azure APP Function. Hope you love this article. Stay connected with me!