连接到 Power BI API 时收到 'Forbidden (403)'

Receiving a 'Forbidden (403)' when connecting to Power BI API

我们一直在努力遵循 this Power BI article 以便我们可以将 reports/dashboards 嵌入到我们的 SaaS 产品中。具体来说,我们停留在第 3 步,'Create the Embed Token.'

我们能够很好地获得不记名令牌,但是当检索报告的请求最终提交给 API 时,我们收到:操作返回无效状态代码 'Forbidden'

    private static string clientId = "...";
    private static string secretKey = "...";
    private static string groupId = "...";

    static void Main(string[] args)
    {
        string resourceUri = "https://analysis.windows.net/powerbi/api";
        string authorityUri = "https://login.windows.net/common/oauth2/authorize";

        ClientCredential credential = new ClientCredential(clientId, secretKey);
        AuthenticationContext authContext = new AuthenticationContext(authorityUri);

        var token = authContext.AcquireTokenAsync(resourceUri, credential).Result.AccessToken;

        var tokenCredentials = new TokenCredentials(token, "Bearer");

        using (var client = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials))
        {
            var reports = client.Reports.GetReportsInGroupWithHttpMessagesAsync(groupId);

            // !!! - Here's where the exception is thrown
            // !!! -- Operation returned an invalid status code 'Forbidden'
            var report = reports.Result.Body;
        }
    }

这是我们尝试过的方法:

您正在使用客户端凭据流获取 Power BI 的令牌 API。目前,Power BI REST API 仅支持委派权限,不支持任何应用程序权限。因此您的访问令牌无法获得足够的访问权限。要使用 Power BI,身份验证需要基于特定用户。相关话题 and 供大家参考。

根据您的 document,场景是应用程序拥有对数据的访问权限。用户不一定是 Power BI 用户,应用程序控制最终用户的身份验证和访问。然后就可以使用resource owner flow来获取token了。

A sample of this is available within Controllers\HomeController.cs of the App Owns Data sample.

根据代码示例,它使用用户密码凭据而不是应用程序凭据获取令牌:

            // 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);

请参阅 Authenticate users and get an Azure AD access token for your Power BI app 并检查 Access token for non-Power BI users (app owns data) 部分。

我们发现组 (App Workspace) 需要由使用 Azure 进行身份验证的同一用户拥有。此用户还需要列为您 register.Once 您修改权限的 Azure 应用程序的所有者。不要忘记重新发布 powerbi 报告,只有它反映了更改。

从 Power BI 获取 真实 异常的最佳方法是添加 DelegatingHandler 并查看 headers / body消息。

https://github.com/Microsoft/PowerBI-CSharp/compare/master...mikeblakeuk:feature/exceptionHandler

这是因为您正尝试使用 SPN 身份验证调用我的工作区中的一些 Reports/Dashboards。目前这是 SPN

的已知限制

Reference