cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
send2prasan Regular Visitor
Regular Visitor

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.

1 ACCEPTED SOLUTION

Accepted Solutions
jhorgan New Member
New Member

Re: Embed Power BI dashboard in ASP.Net core

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 

 

 

View solution in original post

5 REPLIES 5
Moderator Eric_Zhang
Moderator

Re: Embed Power BI dashboard in ASP.Net core


@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 New Member
New Member

Re: Embed Power BI dashboard in ASP.Net core

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 

 

 

View solution in original post

borlip Regular Visitor
Regular Visitor

Re: Embed Power BI dashboard in ASP.Net core

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

OutdoorEd Frequent Visitor
Frequent Visitor

Re: Embed Power BI dashboard in ASP.Net core

So when is Microsoft going to provide a sample for Net Core? I have been migrating my SaaS app from MVC to Net COre 2.2 in order to be ready for 3.0 which will go preview live soon and there still isn't a way to get Power BI Embedded to work. While that may have been an acceptable level of support when MS was charging only $10/month for Power BI Embedded, under the current pricing tier, they need to do much better. Net Core 3.0 is supposed to be the wave of the future.

Highlighted
vega Member
Member

Re: Embed Power BI dashboard in ASP.Net core

Are there any updates to this? We are moving to .Net Core 3.0 and it would be nice to have examples to guide us through the process.

Helpful resources

Announcements
Meet the 2020 Season 1 Power BI Super Users!

Meet the 2020 Season 1 Power BI Super Users!

It’s the start of a new Super User season! Learn all about the new Super Users and brand-new tiered recognition system.

Super User Challenge: Can You Solve These?

Super User Challenge: Can You Solve These?

We're celebrating the start of the New Super User season with our first ever Super User 'Can You Solve These?' challenge.

Power BI Desktop Update - February 2020

Power BI Desktop Update - February 2020

We are super excited for our update this month, as we are releasing two of our top community requests!

Power Platform Online Conference

Power Platform Online Conference

Join us for the first ever Power Platform Online Conference!

Top Solution Authors
Top Kudoed Authors