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,

  1. Overview of Power BI Embedded
  2. Register the Power BI Application in Azure AD
  3. Common steps to Embed Power BI report to the third party application

Now, let’s get started!

Create an Azure App Function

  1. Open Azure Portal.
  2. Go to All Resources > Add > Serverless Function App.
     Serverless Function App
  3. Give a name for your App function.
    Here, my application name = PBIReportEmbedded
    Click on the Create button.
    Create button
  4. Now, from the left navigation,> Click on Function Apps > Click on PBIReportEmbedded which we have created in Step 3.
    PBIReportEmbedded
  5. Click on Application Setting.
    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
    
    Key-value Pairs
  7. From Functions > Click on + icon > Select Webhook + API > CSharp > Create this function.
    Select Webhook
  8. Click on View Files
    View Files
  9. Add a file named “project.json”.
    Project.json
  10. 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"
          }
        }
      }
    }
  11. Open the “run.csx” file.
    Run.csx
  12. 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; }
    }
    
  13. Run the code. You will get the following output.
     Run the code
  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.
    Grant Permission
  15. 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!


Similar Articles