首页 > 解决方案 > Power BI embed API 访问令牌请求通过 Postman 而不是通过代码工作

问题描述

我正在将 Power BI 仪表板嵌入到 Blazor Web 应用程序中,但我似乎完全无法检索访问令牌。我正在使用以下代码,取自本教程并修改为使用客户端凭据代替密码:

private async Task<string> GetPowerBIAccessToken()
{
    using (var client = new HttpClient())
    {
        var form = new Dictionary<string, string>();

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

        client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

        var request = new HttpRequestMessage();

        request.SetBrowserRequestMode(BrowserRequestMode.NoCors);
        request.Method = HttpMethod.Post;
        request.RequestUri = new Uri(_configuration["PowerBI:AuthorityUrl"]);
        request.Content = new FormUrlEncodedContent(form);

        using (var response = await client.SendAsync(request))
        {
            var body = await response.Content.ReadAsStringAsync();
            var jsonBody = JObject.Parse(body);
            var errorToken = jsonBody.SelectToken("error");
            if (errorToken != null)
            {
                throw new Exception(errorToken.Value<string>());
            }
            return jsonBody.SelectToken("access_token").Value<string>();
        }
    }
}

此代码在浏览器中产生以下错误:Unhandled exception rendering component: Error reading JObject from JsonReader. Path '', line 0, position 0..

这是因为该行var jsonBody = JObject.Parse(body)正在尝试解析 JSON 响应,但响应为空。令人费解的是,这并不是因为请求失败——事实上它返回了 200,而是一个完全空白的响应正文:

请求标头和表单数据

空白回复

更令人困惑的是,在 Postman 中重构的完全相同的请求返回的结果很好:

成功的邮递员请求和响应

我确信邮递员和我忽略的代码之间存在一些基本的区别,但是我一直在努力解决这个问题几个小时,但没有运气。我非常感谢任何指导。首先十分感谢。

标签: c#.netasp.net-corepowerbiblazor

解决方案


我是个白痴。我收到了一个不透明的响应,因为这正是我配置请求的方式。

我遇到这个问题的全部原因是我在尝试发出原始请求时遇到了 CORS 错误:

Access to fetch at 'https://login.microsoftonline.com/cattywampus.microsoftonline.com/oauth2/token' from origin 'https://localhost:44333' 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.

因此,我添加request.SetBrowserRequestMode(BrowserRequestMode.NoCors)到配置中,不理解不透明的响应意味着响应将是空白的,无论结果如何。

显然,这并没有为我解决任何问题。如果您遇到上述错误消息,请确保您知道不透明的响应意味着即使 200 也不会返回任何类型的有效负载。这就是不透明的意思。至少我今天学到了一些东西。


推荐阅读