对用户进行身份验证并获取 Power BI 应用的 Azure AD 访问令牌Authenticate users and get an Azure AD access token for your Power BI app

了解如何在 Power BI 应用中对用户进行身份验证,并检索要用于 REST API 的访问令牌。Learn how you can authenticate users within your Power BI application and retrieve an access token to use with the REST API.

必须先获取 Azure Active Directory (Azure AD) 身份验证访问令牌(简称“访问令牌”),才能调用 Power BI REST API。Before you can call the Power BI REST API, you need to get an Azure Active Directory (Azure AD) authentication access token (access token). 使用访问令牌允许应用访问 Power BI 仪表板、磁贴和报表。An access token is used to allow your app access to Power BI dashboards, tiles and reports. 若要了解有关 Azure Active Directory 访问令牌流的详细信息,请参阅 Azure AD 授权代码授予流To learn more about Azure Active Directory access token flow, see Azure AD Authorization Code Grant Flow.

访问令牌的检索方式不同,具体视内容的嵌入方式而定。Depending on how you are embedding content, the access token will be retrieved differently. 本文使用了两种不同方法。Two different approaches are used within this article.

Power BI 用户(用户拥有数据)的访问令牌Access token for Power BI users (user owns data)

此示例适用于用户使用组织登录凭据手动登录 Azure AD 的情况。This example is for when your users will manually log into Azure AD with their organziation login. 为 Power BI 用户(访问在 Power BI 服务中有权访问的内容)嵌入内容时,使用此示例。This is used when embedding content for Power BI users that will access content they have access to within the Power BI service.

从 Azure AD 获取授权代码Get an authorization code from Azure AD

获取访问令牌的第一步是从 Azure AD 获取授权代码。The first step to get an access token is to get an authorization code from Azure AD. 若要执行此操作,请构造具有以下属性的查询字符串,并重定向到 Azure ADTo do this, you construct a query string with the following properties, and redirect to Azure AD.

授权代码查询字符串Authorization code query string

var @params = new NameValueCollection
{
    //Azure AD will return an authorization code. 
    //See the Redirect class to see how "code" is used to AcquireTokenByAuthorizationCode
    {"response_type", "code"},

    //Client ID is used by the application to identify themselves to the users that they are requesting permissions from. 
    //You get the client id when you register your Azure app.
    {"client_id", Properties.Settings.Default.ClientID},

    //Resource uri to the Power BI resource to be authorized
    // https://analysis.windows.net/powerbi/api
    {"resource", Properties.Settings.Default.PowerBiAPI},

    //After user authenticates, Azure AD will redirect back to the web app
    {"redirect_uri", "http://localhost:13526/Redirect"}
};

构造查询字符串后,重定向到 Azure AD 以获取授权代码After you construct a query string, you redirect to Azure AD to get an authorization code. 下面是构造授权代码查询字符串的并重定向到 Azure AD 的完整 C# 方法。Below is a complete C# method to construct an authorization code query string, and redirect to Azure AD. 获取授权代码后,将使用授权代码获取访问令牌After you have the authorization code, you get an access token using the authorization code.

然后,在 redirect.aspx.cs 中,调用 AuthenticationContext.AcquireTokenByAuthorizationCode 生成令牌。Within redirect.aspx.cs, AuthenticationContext.AcquireTokenByAuthorizationCode will then be called to generate the token.

获取授权代码Get authorization code

protected void signInButton_Click(object sender, EventArgs e)
{
    //Create a query string
    //Create a sign-in NameValueCollection for query string
    var @params = new NameValueCollection
    {
        //Azure AD will return an authorization code. 
        //See the Redirect class to see how "code" is used to AcquireTokenByAuthorizationCode
        {"response_type", "code"},

        //Client ID is used by the application to identify themselves to the users that they are requesting permissions from. 
        //You get the client id when you register your Azure app.
        {"client_id", Properties.Settings.Default.ClientID},

        //Resource uri to the Power BI resource to be authorized
        // https://analysis.windows.net/powerbi/api
        {"resource", Properties.Settings.Default.PowerBiAPI},

        //After user authenticates, Azure AD will redirect back to the web app
        {"redirect_uri", "http://localhost:13526/Redirect"}
    };

    //Create sign-in query string
    var queryString = HttpUtility.ParseQueryString(string.Empty);
    queryString.Add(@params);

    //Redirect authority
    //Authority Uri is an Azure resource that takes a client id to get an Access token
    // AADAuthorityUri = https://login.windows.net/common/oauth2/authorize/
    string authorityUri = Properties.Settings.Default.AADAuthorityUri;
    var authUri = String.Format("{0}?{1}", authorityUri, queryString);
    Response.Redirect(authUri);
}

通过授权代码获取访问令牌Get an access token from authorization code

现在应该已有从 Azure AD 获取的授权代码。You should now have an authorization code from Azure AD. Azure AD 使用授权代码重定向回 Web 应用后,请使用授权代码获取访问令牌。Once Azure AD redirects back to your web app with an authorization code, you use the authorization code to get an access token. 下面的 C# 示例可用于重定向页和 default.aspx 页的 Page_Load 事件。Below is a C# sample that you could use in your redirect page and the Page_Load event for your default.aspx page.

可以从 Active Directory 身份验证库 NuGet 包检索 Microsoft.IdentityModel.Clients.ActiveDirectory 命名空间。The Microsoft.IdentityModel.Clients.ActiveDirectory namespace can be retrieved from the Active Directory Authentication Library NuGet package.

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

Redirect.aspx.csRedirect.aspx.cs

using Microsoft.IdentityModel.Clients.ActiveDirectory;

protected void Page_Load(object sender, EventArgs e)
{
    //Redirect uri must match the redirect_uri used when requesting Authorization code.
    string redirectUri = String.Format("{0}Redirect", Properties.Settings.Default.RedirectUrl);
    string authorityUri = Properties.Settings.Default.AADAuthorityUri;

    // Get the auth code
    string code = Request.Params.GetValues(0)[0];

    // Get auth token from auth code
    TokenCache TC = new TokenCache();

    AuthenticationContext AC = new AuthenticationContext(authorityUri, TC);
    ClientCredential cc = new ClientCredential
        (Properties.Settings.Default.ClientID,
        Properties.Settings.Default.ClientSecret);

    AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc);

    //Set Session "authResult" index string to the AuthenticationResult
    Session[_Default.authResultString] = AR;

    //Redirect back to Default.aspx
    Response.Redirect("/Default.aspx");
}

Default.aspxDefault.aspx

using Microsoft.IdentityModel.Clients.ActiveDirectory;

protected void Page_Load(object sender, EventArgs e)
{

    //Test for AuthenticationResult
    if (Session[authResultString] != null)
    {
        //Get the authentication result from the session
        authResult = (AuthenticationResult)Session[authResultString];

        //Show Power BI Panel
        signInStatus.Visible = true;
        signInButton.Visible = false;

        //Set user and token from authentication result
        userLabel.Text = authResult.UserInfo.DisplayableId;
        accessTokenTextbox.Text = authResult.AccessToken;
    }
}

非 Power BI 用户(应用拥有数据)的访问令牌Access token for non-Power BI users (app owns data)

这种方法通常用于 ISV 类型的应用,即应用拥有数据访问权限。This approach is typically used for ISV type applications where the app owns access to the data. 用户不一定是 Power BI 用户,且应用控制最终用户的身份验证和访问权限。Users will not necessarily be Power BI users and the application controls authentication and access for the end users.

若要使用这种方法,请使用一个是 Power BI Pro 用户的主帐户。For this approach, you will use a single master account that is a Power BI Pro user. 此帐户的凭据存储在应用名下。The credentials for this account are stored with the application. 应用使用这些存储的凭据进行 Azure AD 身份验证。The application will authenticate against Azure AD with those stored credentials. 下面显示的示例代码来自“应用拥有数据”示例The example code shown below comes from the App owns data sample

HomeController.csHomeController.cs

using Microsoft.IdentityModel.Clients.ActiveDirectory;

// Create a user password cradentials.
var credential = new UserPasswordCredential(Username, Password);

// Authenticate using created credentials
var authenticationContext = new AuthenticationContext(AuthorityUrl);
var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

if (authenticationResult == null)
{
    return View(new EmbedConfig()
    {
        ErrorMessage = "Authentication Failed."
    });
}

var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

若要了解如何使用 await,请参阅 await(C# 参考)For information on how to use await, see await (C# Reference)

后续步骤Next steps

至此,已拥有访问令牌,可以调用 Power BI REST API 嵌入内容了。Now that you have the access token, you can call the Power BI REST API to embed content. 有关如何嵌入内容的信息,请参阅如何嵌入 Power BI 仪表板、报表和磁贴For information on how to embed your content, see How to embed your Power BI dashboards, reports and tiles.

更多问题?More questions? 尝试咨询 Power BI 社区Try asking the Power BI Community