您可以使用Azure Active Directory Authentication Libraries 获取 Power BI 的访问令牌。获取它的最简单方法是安装 Microsoft.IdentityModel.Clients.ActiveDirectory NuGet 包。然后要获取访问令牌,您需要调用AcquireTokenAsync 方法。您可以这样做:
private static string redirectUri = "https://login.live.com/oauth20_desktop.srf";
private static string resourceUri = "https://analysis.windows.net/powerbi/api";
private static string authorityUri = "https://login.windows.net/common/oauth2/authorize";
// Obtain at https://dev.powerbi.com/apps
private static string clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
private static AuthenticationContext authContext = new AuthenticationContext(authorityUri, new TokenCache());
private async void btnAuthenticate_ClickAsync(object sender, EventArgs e)
{
var authenticationResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Auto));
if (authenticationResult == null)
MessageBox.Show("Call failed.");
else
MessageBox.Show(authenticationResult.AccessToken);
}
最后一个参数是 PromptBehavior.Auto。这意味着系统将提示您输入凭据,除非您的身份保存在此计算机上。此外,当没有同意访问此应用程序时,也会提示用户。身份验证以交互方式执行 - 它期望会有一个人,在需要时输入凭据。如果您想以非交互方式获取访问令牌,您可以在代码中使用用户名和密码。在这种情况下,获取访问令牌的方法应该如下所示:
private void btnAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationResult authenticationResult = null;
// First check is there token in the cache
try
{
authenticationResult = authContext.AcquireTokenSilentAsync(resourceUri, clientId).Result;
}
catch (AggregateException ex)
{
AdalException ex2 = ex.InnerException as AdalException;
if ((ex2 == null) || (ex2 != null && ex2.ErrorCode != "failed_to_acquire_token_silently"))
{
MessageBox.Show(ex.Message);
return;
}
}
if (authenticationResult == null)
{
var uc = new UserPasswordCredential("user@example.com", "<EnterStrongPasswordHere>"); // Or parameterless if you want to use Windows integrated auth
try
{
authenticationResult = authContext.AcquireTokenAsync(resourceUri, clientId, uc).Result;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.InnerException == null ? "" : Environment.NewLine + ex.InnerException.Message);
return;
}
}
if (authenticationResult == null)
MessageBox.Show("Call failed.");
else
MessageBox.Show(authenticationResult.AccessToken);
}
请注意,如果您的应用未获得同意,此调用可能会失败。为此,请转到 Azure 门户 -> Azure Active Directory -> 应用注册并找到您的应用。然后打开应用的设置,在所需权限中选择 Power BI 服务并单击授予权限:
此时,您可以使用此访问令牌来执行 REST API 调用或在您的应用中嵌入元素。此令牌提供对用户可以访问的所有内容的访问权限,并且当您在门户中注册您的应用程序时,它已被允许访问。但是,如果您想为一个特定报告(或磁贴或仪表板)生成令牌,则可以调用一些 Embed Token 方法,例如GenerateTokenInGroup(使用 ADAL 访问令牌在生成嵌入式令牌的请求标头中验证您自己)。