[英]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.