Forum Discussion

send2prasan's avatar
send2prasan
Helper I
8 years ago
Solved

Embed Power BI dashboard in ASP.Net core

Dear All,

 

We would like to Embed power bi dashboard in ASP.Net core web application not MVC based. I am struggling get a working example nor I am able to find step-by-step process to build this feature.

 

Eveyone leads into following exampe which is build on MVC,

 

https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-embed-sample-app-owns-data/  

 

Can someone suggest me how to embed power bi dashboard on core asp.net web application. 

 

Thanks,

Prasanna V.

  • jhorgan's avatar
    jhorgan
    8 years ago

    Hi, 

     

    The above suggestion from Eric_Zang won't work for Asp .Net Core as the UserPasswordCredentials is not supported in .NET Core. See: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/482

     

    I came across the same issues recently. My work-around was to use make a native REST call to the Azure AD for a token. I was pointed to this approach here: https://github.com/Microsoft/PowerBI-CSharp/issues/116

     

    My solution is as follows:

     

    Replace the following from Eric_Zang's example

    var credential = new UserPasswordCredential(Username, Password);
    
    // Authenticate using created credentials
    var authenticationContext = new AuthenticationContext(AuthorityUrl);
    var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

    with:

     

    var authenticationResult = await AuthenticateAsync();
    
    private static async Task<OAuthResult> AuthenticateAsync()
    {
        var oauthEndpoint = new Uri(AuthorityUrl);
    
        using (var client = new HttpClient())
        {
            var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("resource", ResourceUrl),
                new KeyValuePair<string, string>("client_id", ClientId),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", Username),
                new KeyValuePair<string, string>("password", Password),
                new KeyValuePair<string, string>("scope", "openid"),
            }));
    
            var content = await result.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<OAuthResult>(content);
        }
    }
    
    class OAuthResult
    {
        [JsonProperty("token_type")]
        public string TokenType { get; set; }
        [JsonProperty("scope")]
        public string Scope { get; set; }
        [JsonProperty("experies_in")]
        public int ExpiresIn { get; set; }
        [JsonProperty("ext_experies_in")]
        public int ExtExpiresIn { get; set; }
        [JsonProperty("experies_on")]
        public int ExpiresOn { get; set; }
        [JsonProperty("not_before")] 
        public int NotBefore { get; set; }
        [JsonProperty("resource")]
        public Uri Resource { get; set; }
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }
        [JsonProperty("refresh_token")]
        public string RefreshToken { get; set; }
    }

    I understand that using the OAuth Password grant was removed from ADAL for .NET Core to strongly discourage transporting and saving user credentials.

     

    I would like very much for a recommended approach for using PowerBI Embedded in as Asp .Net Core app.

     

    Hope this helps.

    Jeremy 

     

     

6 Replies

  • Eric_Zhang's avatar
    Eric_Zhang
    Microsoft Employee

    send2prasan wrote:

    Dear All,

     

    We would like to Embed power bi dashboard in ASP.Net core web application not MVC based. I am struggling get a working example nor I am able to find step-by-step process to build this feature.

     

    Eveyone leads into following exampe which is build on MVC,

     

    https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-embed-sample-app-owns-data/  

     

    Can someone suggest me how to embed power bi dashboard on core asp.net web application. 

     

    Thanks,

    Prasanna V.


    send2prasan

    Where are you stuck? Here's a static HTML for your reference.

    <html>
    <script src="https://microsoft.github.io/PowerBI-JavaScript/demo/node_modules/jquery/dist/jquery.js"></script>
    <script src="https://microsoft.github.io/PowerBI-JavaScript/demo/node_modules/powerbi-client/dist/powerbi.js"></script>
    
    <script type="text/javascript"> 
    window.onload = function () {
     // Read embed application token from Model
        var accessToken = "H4sIAAAAAAAEAC2Wxa7FDHKExxxxxxxxigEVoLAAA=";
    
        // Read embed URL from Model
        var embedUrl = "https://msit.powerbi.com/dashboardEmbed?dashboardId=66d6daxxxxx96-13e88c1cbdde&groupId=dc581184-a20xxxxx6b6c15";
    
        // Read dashboard Id from Model
        var embedDashboardId = "66d6dafxxxx-13e88c1cbdde";
    
        // Get models. models contains enums that can be used.
        var models = window['powerbi-client'].models	
    
        // Embed configuration used to describe the what and how to embed.
        // This object is used when calling powerbi.embed.
        // This also includes settings and options such as filters.
        // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
        var config = {
            type: 'dashboard',
            tokenType: models.TokenType.Embed,
            accessToken: accessToken,
            embedUrl: embedUrl,
    		pageView: "fitToWidth",
            id: embedDashboardId
        };
    
        // Get a reference to the embedded dashboard HTML element
        var dashboardContainer = $('#dashboardContainer')[0] ;
    
        // Embed the dashboard and display it within the div container.
        var dashboard = powerbi.embed(dashboardContainer, config); 	 
    } 
    </script> 
    <p><input type="hidden" id="Textinput" /></p> 
    <div id="dashboardContainer"></div>
    </html>  

     

    As to how to get the embedded token, you can reference below snippet or the REST API GenerateToken

               string ClientId = {clientid of the registered native app};
                // Create a user password cradentials.
                var credential = new UserPasswordCredential(Username, Password);
    
                // Authenticate using created credentials
                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);
    
                if (authenticationResult == null)
                {
                    return View(new EmbedConfig()
                    {
                        ErrorMessage = "Authentication Failed."
                    });
                }
    
                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
    
                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
                {
                    // Get a list of dashboards.
                    var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(GroupId);
    
                    // Get the first report in the group.
                    var dashboard = dashboards.Value.FirstOrDefault();
    
                    if (dashboard == null)
                    {
                        return View(new EmbedConfig()
                        {
                            ErrorMessage = "Group has no dashboards."
                        });
                    }
    
                    // Generate Embed Token.
                    var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                    var embedToken= await client.Dashboards.GenerateTokenInGroupAsync(GroupId, dashboard.Id, generateTokenRequestParameters);
    
    • jhorgan's avatar
      jhorgan
      New Member

      Hi, 

       

      The above suggestion from Eric_Zang won't work for Asp .Net Core as the UserPasswordCredentials is not supported in .NET Core. See: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/482

       

      I came across the same issues recently. My work-around was to use make a native REST call to the Azure AD for a token. I was pointed to this approach here: https://github.com/Microsoft/PowerBI-CSharp/issues/116

       

      My solution is as follows:

       

      Replace the following from Eric_Zang's example

      var credential = new UserPasswordCredential(Username, Password);
      
      // Authenticate using created credentials
      var authenticationContext = new AuthenticationContext(AuthorityUrl);
      var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

      with:

       

      var authenticationResult = await AuthenticateAsync();
      
      private static async Task<OAuthResult> AuthenticateAsync()
      {
          var oauthEndpoint = new Uri(AuthorityUrl);
      
          using (var client = new HttpClient())
          {
              var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
              {
                  new KeyValuePair<string, string>("resource", ResourceUrl),
                  new KeyValuePair<string, string>("client_id", ClientId),
                  new KeyValuePair<string, string>("grant_type", "password"),
                  new KeyValuePair<string, string>("username", Username),
                  new KeyValuePair<string, string>("password", Password),
                  new KeyValuePair<string, string>("scope", "openid"),
              }));
      
              var content = await result.Content.ReadAsStringAsync();
              return JsonConvert.DeserializeObject<OAuthResult>(content);
          }
      }
      
      class OAuthResult
      {
          [JsonProperty("token_type")]
          public string TokenType { get; set; }
          [JsonProperty("scope")]
          public string Scope { get; set; }
          [JsonProperty("experies_in")]
          public int ExpiresIn { get; set; }
          [JsonProperty("ext_experies_in")]
          public int ExtExpiresIn { get; set; }
          [JsonProperty("experies_on")]
          public int ExpiresOn { get; set; }
          [JsonProperty("not_before")] 
          public int NotBefore { get; set; }
          [JsonProperty("resource")]
          public Uri Resource { get; set; }
          [JsonProperty("access_token")]
          public string AccessToken { get; set; }
          [JsonProperty("refresh_token")]
          public string RefreshToken { get; set; }
      }

      I understand that using the OAuth Password grant was removed from ADAL for .NET Core to strongly discourage transporting and saving user credentials.

       

      I would like very much for a recommended approach for using PowerBI Embedded in as Asp .Net Core app.

       

      Hope this helps.

      Jeremy 

       

       

      • borlip's avatar
        borlip
        Kudo Kingpin

        It's quite annoying that Microsoft were only able to provide samples for a full .net framework and not for .net core. At the same time, MS' AD team decides not to include UserName/Password authentication in .net standard version of the framework