在我的项目中,我试图在没有交互式登录的情况下从 powerBI 获取嵌入报告信息。到目前为止,我能够使用“密码”授权获取信息;当我尝试使用“密码”授权做同样的事情时,它给了我“未经授权”的错误。我在我的 github 链接中托管了该应用程序。
使用说明:
- 获取访问令牌以获取访问令牌进行身份验证。
var form = new Dictionary<string, string>();
form["grant_type"] = "password";
form["username"] = _config.Azure.Username;
form["password"] = _config.Azure.Password;
form["client_id"] = _config.Azure.ClientID;
form["client_secret"] = _config.Azure.ClientSecret;
form["scope"] = string.Join(" ",_config.Azure.Scopes);
var content = new FormUrlEncodedContent(form);
var input = new HttpInputModel
{
BaseAddress = $"{_config.Azure.AuthorityUrl}/{_config.Azure.TenantID}/",
Content = content,
Headers = new Dictionary<string, string>
{
{ "Content-Type","application/x-www-form-urlencoded" }
},
Url = "oauth2/v2.0/token"
};
- 使用上面的 accesstoken 来获取 powerBI 客户端。
var token = await _azureService.GetAccessToken();
var tokenCredentials = new TokenCredentials(token, "Bearer");
_client = new PowerBIClient(new Uri(_config.PowerBI.ApiUrl), tokenCredentials);
- 使用客户端检索报告信息。
var workspaceId = reportInput.WorkspaceID;
var reportId = reportInput.ReportID;
var report = await _client.Reports.GetReportInGroupAsync(workspaceId, reportId);
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponse = await _client.Reports.GenerateTokenAsync(workspaceId, reportId, generateTokenRequestParameters);
var output = new ReportOutput
{
Username = _config.PowerBI.Username,
EmbdedToken = tokenResponse,
EmbedUrl = report.EmbedUrl,
Id = reportInput.ReportID.ToString()
};
return output;
结论:在第 1 步:您可以看到我正在使用密码授予类型。当我尝试用“client_crdentials”代替“password”并且没有给出“username”和“password”时。生成的“accesstoken”在步骤 3 中给出了“未授权”异常。
注意:我尝试在很多论坛中搜索,其中一些说我们可以使用“serviceprincipal”。但我无法做到这一点。