top of page
Writer's pictureDhruvin Shah

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

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,

  • 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

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. Serialisation;  

  6. using Microsoft.IdentityModel.Clients.ActiveDirectory;  

  7. using Microsoft.PowerBI.Api.V2;  

  8. using Microsoft.PowerBI.Api.V2.Models;  

  9. using Microsoft. Rest;  

  10. // Static Values

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

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

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

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

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

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

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

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

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

  20. {  

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

  22. var credential = new UserPasswordCredential(username, password);      

  23. var authenticationContext = new AuthenticationContext(authorityUrl);      

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

  25. string accessToken = authenticationResult.AccessToken;      

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

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

  28. {  

  29. // Embed URL         

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

  31. string embedUrl = report.EmbedUrl;  

  32. // Embed Token         

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

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

  35. // JSON Response         

  36. EmbedContent data = new EmbedContent();          

  37. data.EmbedToken = embedToken.Token;          

  38. data.EmbedUrl = embedUrl;          

  39. data.ReportId = reportId;          

  40. JavaScriptSerializer js = new JavaScriptSerializer();  

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

  42. // Return Response

  43. return new HttpResponseMessage(HttpStatusCode.OK)           

  44. {              

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

  46. };      

  47. }  

  48. }  

  49. public class EmbedContent  

  50. {  

  51. public string EmbedToken 

  52. getset

  53. }  

  54. public string EmbedUrl 

  55. getset

  56. }  

  57. public string ReportId 

  58. getset;

  59.  }  

  60. }  


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!

0 comments

Comentários


bottom of page