Power BI访问令牌的授予无效

时间:2018-10-16 19:20:46

标签: javascript azure powerbi

当我尝试获取Power Bi App拥有数据的访问令牌时,我遇到错误。我通过邮递员通过传递Power Bi Pro的gtrant_type,范围,资源,用户名和密码,client_id来对它进行测试。

有人可以给我正确解决此错误的方法吗?

{
    "error": "invalid_grant",
    "error_description": "AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password\r\nTrace ID: 72bcce14-c8e5-4a01-998e-622047583700\r\nCorrelation ID: 6e622466-1590-4458-836f-e71be2eb5fca\r\nTimestamp: 2018-10-16 19:04:20Z",
    "error_codes": [
        70002,
        50126
    ],
    "timestamp": "2018-10-16 19:04:20Z",
    "trace_id": "72bcce14-c8e5-4a01-998e-622047583700",
    "correlation_id": "6e622466-1590-4458-836f-e71be2eb5fca"
}

1 个答案:

答案 0 :(得分:0)

您没有在问题中提供足够的细节。

假设您正在使用新的Power BI嵌入式基础结构V2 API。

using Microsoft.PowerBI.Api.V2;

在这种情况下,从MS的代码示例开始: https://github.com/Microsoft/PowerBI-Developer-Samples/tree/master/App%20Owns%20Data/PowerBIEmbedded_AppOwnsData

我在这里的HomController中获得令牌的方式与之相同:https://github.com/Microsoft/PowerBI-Developer-Samples/blob/master/App%20Owns%20Data/PowerBIEmbedded_AppOwnsData/Controllers/HomeController.cs

public async Task<ActionResult> EmbedReport(string username, string roles)
    {
        var result = new EmbedConfig();
        try
        {
            result = new EmbedConfig { Username = username, Roles = roles };
            var error = GetWebConfigErrors();
            if (error != null)
            {
                result.ErrorMessage = error;
                return View(result);
            }

            // 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, ApplicationId, credential);

            if (authenticationResult == null)
            {
                result.ErrorMessage = "Authentication Failed.";
                return View(result);
            }

            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 reports.
                var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);

                // No reports retrieved for the given workspace.
                if(reports.Value.Count() == 0)
                {
                    result.ErrorMessage = "No reports were found in the workspace";
                    return View(result);
                }

                Report report;
                if (string.IsNullOrWhiteSpace(ReportId))
                {
                    // Get the first report in the workspace.
                    report = reports.Value.FirstOrDefault();
                }
                else
                {
                    report = reports.Value.FirstOrDefault(r => r.Id == ReportId);
                }

                if (report == null)
                {
                    result.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid.";
                    return View(result);
                }

                var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);
                result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
                result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                GenerateTokenRequest generateTokenRequestParameters;
                // This is how you create embed token with effective identities
                if (!string.IsNullOrWhiteSpace(username))
                {
                    var rls = new EffectiveIdentity(username, new List<string> { report.DatasetId });
                    if (!string.IsNullOrWhiteSpace(roles))
                    {
                        var rolesList = new List<string>();
                        rolesList.AddRange(roles.Split(','));
                        rls.Roles = rolesList;
                    }
                    // Generate Embed Token with effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });
                }
                else
                {
                    // Generate Embed Token for reports without effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                }

                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);

                if (tokenResponse == null)
                {
                    result.ErrorMessage = "Failed to generate embed token.";
                    return View(result);
                }

                // Generate Embed Configuration.
                result.EmbedToken = tokenResponse;
                result.EmbedUrl = report.EmbedUrl;
                result.Id = report.Id;

                return View(result);
            }
        }
        catch (HttpOperationException exc)
        {
            result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault());
        }
        catch (Exception exc)
        {
            result.ErrorMessage = exc.ToString();
        }

        return View(result);
    }