【问题标题】:Power BI Embed appears to be literally impossible to authenticate in a Blazor Webassembly applicationPower BI Embed 似乎无法在 Blazor Webassembly 应用程序中进行身份验证
【发布时间】:2021-05-29 05:54:48
【问题描述】:

我和我的团队已经尝试了我们能想到的所有方法。没有任何效果。我们已经准备好放弃了。

尝试 1 - 使用 HttpClient() 的 POST 请求:

public class PowerBIComponent : ComponentBase
{
    [Inject] IConfiguration Config { get; set; }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var token = await GetAccessToken();
        }
    }

    public async Task<string> GetAccessToken()
    {
        var form = new Dictionary<string, string>();

        form["grant_type"] = "client_credentials";
        form["client_id"] = Config["PowerBI:ClientId"];
        form["client_secret"] = Config["PowerBI:ClientId"];
        form["scope"] = "https://graph.microsoft.com/.default";

        var formContent = new FormUrlEncodedContent(form);

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

            var response = await client.PostAsync(Config["PowerBI:AuthorityUrl"], formContent);

            return response.Content.ToString();
        }
    }
}

这会产生以下错误:

Access to fetch at 'https://login.microsoftonline.com/{our-tenant-id}/oauth2/token' from origin 'https://localhost:44364' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我们的基础设施人员已经配置了所有可以想象的允许来源,但仍未解决此问题。令人费解的是,完全相同的请求在 Postman 中也能正常工作。

尝试 2 - 使用 Microsoft.PowerBI.API 库:

public class PowerBIComponent : ComponentBase
{
    [Inject] IConfiguration Config { get; set; }

    protected async override Task OnInitializedAsync()
    {
        Task.Delay(10000);
    }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var token = await GetAccessToken();
        }
    }

    public async Task<string> GetAccessToken()
    {
        var appConfidential = ConfidentialClientApplicationBuilder.Create(Config["PowerBI:ClientId"])
                            .WithClientSecret(Config["PowerBI:ClientSecret"])
                            .WithAuthority(Config["PowerBI:AuthorityUrl"])
                            .Build();
            
        string[] scopesDefault = new string[] { "https://graph.microsoft.com/.default" };

        var authResult = appConfidential.AcquireTokenForClient(scopesDefault).ExecuteAsync().Result;

        return authResult.AccessToken;
    }
}

这会产生以下错误:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Property UseDefaultCredentials is not supported.

快速谷歌搜索导致this post,这似乎表明这是库本身无法避免的兼容性问题,尚未解决。

尝试 3 - JSInterop 和普通的旧 Javascript:

window.PowerBI = {
getAccessToken: function () {
    var form = {
        grant_type: "client_credentials",
        client_id: "my_super_secret_client_id",
        client_secret: "my_super_duper_client_secret",
        scope: "https://graph.microsoft.com/.default"
    }

    $.ajax({
        url: 'https://login.microsoftonline.com/my-tenant-id-goes-here/oauth2/token',
        type: "POST",
        contentType: 'application/x-www-form-urlencoded',
        data: form,
        success: function (result) {
            console.log(result);
        },
        error: function (xhr, resp, text) {
            console.log(xhr, resp, text);
        }
    });
}

这会产生与使用 HttpClient() 时相同的 CORS 错误:

Access to XMLHttpRequest at 'https://login.microsoftonline.com/dccb27bf-99c4-4985-b8d7-7581887a825e/oauth2/token' from origin 'https://localhost:44334' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我们只是试图在我们的 Blazor Webassembly 应用程序中嵌入 Power BI 报表,但似乎绝对不可能通过检索用于嵌入任何内容的访问令牌的阶段。我们基本上处于完全放弃 Webassembly 并尝试将所有内容转移到 Blazor Server 的地步。我们有没有希望不必这样做?

【问题讨论】:

标签: javascript c# powerbi blazor-webassembly powerbi-embedded


【解决方案1】:

首先:您需要在此处注册您的应用:Embed for your organization

第二:创建一个 Blazor Wasm。 Azure Portal->App Registrations中获取clientID和TenantID

dotnet new blazorwasm -au SingleOrg --client-id "{CLIENT ID}" -o {APP NAME} --tenant-id "{TENANT ID}"

最后:你的 Program 类应该是这样的;

        builder.Services.AddMsalAuthentication(options =>
        {
            builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
            options.ProviderOptions.DefaultAccessTokenScopes.Add("https://analysis.windows.net/powerbi/api/Report.Read.All");
        });

【讨论】:

  • 我使用上面列出的所有三种方法进行了尝试。不幸的是,他们都没有工作。方法 1 和 3 仍然抛出 CORS 错误,而方法 2 返回Unhandled exception rendering component: Operation is not supported on this platform。还值得注意的是,我们正在寻求“为您的客户嵌入”解决方案,而不是“为您的组织嵌入”解决方案,尽管从访问令牌的角度来看,我认为这并不重要。
  • 请看这个例子,看看它是否可以帮助你...github.com/microsoft/PowerBI-Developer-Samples/tree/master/…
猜你喜欢
  • 2023-01-24
  • 2020-11-02
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
相关资源
最近更新 更多