簡介

在將報表整合到應用程式的 步驟 1使用 Azure AD 註冊 Web 應用程式,您會註冊一個 Web 應用程式,讓您的應用程式可以向 Azure Active Directory 驗證。 在此步驟中,您使用存取權杖Power BI API 以取得報表。

若要取得 Power BI 報表,請使用取得報表作業以查看 Power BI 報表清單。 您可以在報表清單中取得 embedUrl 報告。 取得 embedUrl 報表後,您就可以將報表載入 IFrame

可以呼叫取得報表作業或其他任何 Power BI 作業之前,您必須取得 Azure Active Directory 驗證存取權杖 (存取權杖)。 存取權杖可供您的應用程式存取 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# 方法。 取得報表後,您就可以將報表載入 IFrame。 請參閱步驟 3:將 Power BI 報表載入 IFrame

取得報表

protected void GetReport(int index)
{
    //Configure Reports request
    System.Net.WebRequest request = System.Net.WebRequest.Create(
        String.Format("{0}/Reports",
        baseUri)) as System.Net.HttpWebRequest;

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

    //Get Reports 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
            PBIReports Reports = JsonConvert.DeserializeObject<PBIReports>(reader.ReadToEnd());

            //Sample assumes at least one Report.
            //You could write an app that lists all Reports
            if (Reports.value.Length > 0)
                ReportEmbedUrl.Text = Reports.value[index].embedUrl;
        }
    }
}

//Power BI Reports used to deserialize the Get Reports response.
public class PBIReports
{
    public PBIReport[] value { get; set; }
}
public class PBIReport
{
    public string id { get; set; }
    public string name { get; set; }
    public string webUrl { get; set; }
    public string embedUrl { get; set; }
}

下一個步驟

若要將報表整合到應用程式,你必須將報表載入 IFrame。 在下一個步驟中,您會了解如何將報表載入 IFrame

下一步 >

另請參閱

註冊 Power BI
將報表整合到應用程式中的逐步解說
整合報表範例
設定整合報表範例
Azure AD 授權碼授與流程
取得報表作業
步驟 3:將 Power BI 報表載入 IFrame 中
有其他問題嗎? 試試 Power BI 社群