简介

在将磁贴集成到应用的步骤 1将 Web 应用注册到 Azure AD)中,注册 Web 应用以使你的应用能够验证到 Azure Active Directory。 在此步骤中,使用 访问令牌Power BI API 来获取仪表板。 获取仪表板后,可以获取 Power BI 磁贴。

若要获取 Power BI 仪表板,请使用获取仪表板操作,它将获取 Power BI 仪表板的列表。 从仪表板的列表中,你可以获取仪表板 ID。 拥有仪表板 ID 后,即可获取 Power BI 磁贴。

需要先获取 Azure Active Directory 身份验证访问令牌(下称访问令牌),才能调用获取仪表板操作或任何其他 Power BI 操作。 使用访问令牌允许应用访问 Power BI 仪表板和磁贴。 若要了解有关 Azure Active Directory 访问令牌流的详细信息,请参阅 Azure AD 授权代码授予流。 下一部分将演示如何在 Web 应用中获取访问令牌

获取身份验证访问令牌

下面介绍了如何获取身份验证访问令牌以调用 Power BI 操作。

步骤 1:从 Azure AD 获取授权代码

获取访问令牌的第一步是从 Azure AD 获取授权代码。 若要执行此操作,请构造具有以下属性的查询字符串,并重定向到 Azure AD

授权代码查询字符串

var @params = new NameValueCollection
{
    //Azure AD will return an authorization code.
    {"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", Settings.Default.ClientID},

    //Resource uri to the Power BI resource to be authorized
    //The resource uri is hard-coded for sample purposes
    {"resource", "https://analysis.windows.net/powerbi/api"},

    //After app authenticates, Azure AD will redirect back to the web app. In this sample, Azure AD redirects back
    //to Default page (Default.aspx).
    { "redirect_uri", Settings.Default.RedirectUri}
};

构造查询字符串后,重定向到 Azure AD 以获取授权代码。 下面是构造授权代码查询字符串的并重定向到 Azure AD 的完整 C# 方法。 在下一步中,你将使用授权代码获取访问令牌

获取授权代码

public void GetAuthorizationCode()
{
    //NOTE: Values are hard-coded for sample purposes.
    //Create a query string
    //Create a sign-in NameValueCollection for query string
    var @params = new NameValueCollection
    {
        //Azure AD will return an authorization code.
        {"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", Settings.Default.ClientID},

        //Resource uri to the Power BI resource to be authorized
        //The resource uri is hard-coded for sample purposes
        {"resource", "https://analysis.windows.net/powerbi/api"},

        //After app authenticates, Azure AD will redirect back to the web app. In this sample, Azure AD redirects back
        //to Default page (Default.aspx).
        { "redirect_uri", Settings.Default.RedirectUri}
    };

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

    //Redirect to Azure AD Authority
    //  Authority Uri is an Azure resource that takes a client id and client secret to get an Access token
    //  QueryString contains
    //      response_type of "code"
    //      client_id that identifies your app in Azure AD
    //      resource which is the Power BI API resource to be authorized
    //      redirect_uri which is the uri that Azure AD will redirect back to after it authenticates

    //Redirect to Azure AD to get an authorization code
    Response.Redirect(String.Format("https://login.windows.net/common/oauth2/authorize?{0}", queryString));
}

步骤 2:从授权代码获取访问令牌

在获取访问令牌的第 1 步中,你将从 Azure AD 获取授权代码Azure AD 使用授权代码重定向回 Web 应用后,请使用授权代码获取访问令牌。 下面是获取访问令牌的 C# 方法。 在下一部分中,你将使用访问令牌获取仪表板

获取访问令牌

public string GetAccessToken(string authorizationCode, string clientID, string clientSecret, string redirectUri)
{
    //Redirect uri must match the redirect_uri used when requesting Authorization code.
    //Note: If you use a redirect back to Default, as in this sample, you need to add a forward slash
    //such as http://localhost:13526/

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

    //Values are hard-coded for sample purposes
    string authority = "https://login.windows.net/common/oauth2/authorize";
    AuthenticationContext AC = new AuthenticationContext(authority, TC);
    ClientCredential cc = new ClientCredential(clientID, clientSecret);

    //Set token from authentication result
    return AC.AcquireTokenByAuthorizationCode(
        authorizationCode,
        new Uri(redirectUri), cc).AccessToken;
}

使用访问令牌获取仪表板

拥有访问令牌后,即可调用获取仪表板操作。 获取仪表板操作将返回仪表板列表。 你可从仪表板列表中获取仪表板。 下面是获取仪表板的完整 C# 方法。 拥有仪表板后,即可获取磁贴。 请参阅步骤 3:获取 Power BI 磁贴

获取仪表板

//Get a dashboard id.
protected string GetDashboard(int index)
{
    string dashboardId = string.Empty;

    //Configure tiles request
    System.Net.WebRequest request = System.Net.WebRequest.Create(
        String.Format("{0}Dashboards",
        baseUri)) as System.Net.HttpWebRequest;

    request.Method = "GET";
    request.ContentLength = 0;
    request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken.Value));

    //Get dashboards response from request.GetResponse()
    using (var response = request.GetResponse() as System.Net.HttpWebResponse)
    {
        //Get reader from response stream
        using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
        {
            //Deserialize JSON string
            PBIDashboards dashboards = JsonConvert.DeserializeObject<PBIDashboards>(reader.ReadToEnd());

            //Sample assumes at least one Dashboard with one Tile.
            //You could write an app that lists all tiles in a dashboard
            dashboardId = dashboards.value[index].id;
        }
    }

    return dashboardId;
}

//Power BI Dashboards used to deserialize the Get Dashboards response.
public class PBIDashboards
{
    public PBIDashboard[] value { get; set; }
}
public class PBIDashboard
{
    public string id { get; set; }
    public string displayName { get; set; }
}

下一步

若要将磁贴集成到应用中,你需要获取磁贴。 下一步,你将学习如何 获取 Power BI 磁贴

下一步 >

另请参阅

注册 Power BI
将磁贴集成到应用演练
集成磁贴示例
配置集成磁贴示例
Azure AD 授权代码授予流
获取仪表板操作
步骤 3:获取 Power BI 磁贴
更多问题? 尝试参与 Power BI 社区