[英]Power BI embed API access token request works through Postman but not through code
我正在将 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.
Unhandled exception rendering component: Error reading JObject from JsonReader. Path '', line 0, position 0.
..
这是因为var jsonBody = JObject.Parse(body)
行正在尝试解析 JSON 响应,但响应为空。 令人费解的是,这并不是因为请求失败——事实上它返回了 200,而是一个完全空白的响应正文:
更令人困惑的是,在 Postman 中重构的完全相同的请求返回结果很好:
我确信 Postman 和我忽略的代码之间存在一些基本区别,但我已经为此努力了好几个小时,但没有运气。 我非常感谢任何指导。 首先十分感谢。
这可能是您的安全设置的问题
我是个白痴。 我收到了一个不透明的响应,因为这正是我配置请求的方式。
我遇到这个问题的全部原因是我在尝试发出原始请求时遇到了 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 也不会返回任何类型的有效负载。 这就是不透明的意思。 至少我今天学到了一些东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.