2016年5月2日

[PowerBI]不透過登入UI驗證PowerBI REST API呼叫

在PowerBI的文件中提供了一個範例,此範例會透過Web UI讓使用者登入Azure AD帳號後,取得PowerBI的相關資源,並整合到自己的App中。許多情況下我們希望能夠不必讓使用者透過Web UI登入;此時,會需要透過OAuth 2.0的方式在"Silently”取得Access Token,然後在呼叫PowerBI REST API時在authorization header指定Access Token來存取REST API。

如果需要透過這種方式時,則PowerBI文件中透過https://dev.powerbi/com/apps 註冊App的方式便行不通了,我們必須要回到Azure AD手動來做所有的事情。我先前已經有寫過一篇部落格說明詳細的步驟,如果需要如何設定Azure AD App的詳細步驟可以參考這裡:http://blog.michaelchi.net/2015/07/azure-adazure-service-management-rest.html 

snip_20160502152202

  • 接著給予相對應的權限

snip_20160502152302

  • 記住ClientID

snip_20160502152348

  • 記下Tenant ID

snip_20160502152803

  • 接著,我們需要一隻程式幫我們抓到所有PowerBI上的相關報表、Dashboard…etc
  • 開啟一個Visual Studio專案,這個專案也可以是我們到時要整合的Web App;加入以下的NUGet Package

snip_20160502152606

  • 加入以下程式碼:

protected string GetToken()
{
    var tc = new TokenCache();
    var context = new AuthenticationContext("https://login.windows.net/{tenant ID}");

    var resource = "https://analysis.windows.net/powerbi/api";
    var userCredential = new UserCredential("{login user id:xxx@yyy.zzz}", "{password}
    var tkn = context.AcquireToken(resource, “{native app client id}", userCredential);
   
    return tkn.AccessToken;

}

  • 透過以下程式碼取得Embed Report URL

protected string GetReports(string token)
        {
            string responseContent = string.Empty;

            //The resource Uri to the Power BI REST API resource
            string reportsURL = "https://api.powerbi.com/beta/myorg/reports";
            //string reportsURL = "https://api.powerbi.com/v1.0/myorg/datasets";

            //Configure datasets request
            System.Net.WebRequest request = System.Net.WebRequest.Create(reportsURL) as System.Net.HttpWebRequest;
            request.Method = "GET";
            request.ContentLength = 0;

           
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));
            //Get datasets 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()))
                {
                    var sb = new StringBuilder();
                    responseContent = reader.ReadToEnd();

                    return responseContent;
                }
            }
        }

    • 其回傳值範例如下:

{
"@odata.context":"http://df-msit-scus.analysis.windows.net/beta/myorg/$metadata#reports","value":[
  {
      "id":"xxxxxxxx-cc0a-4aeb-b4c2-xxxxxxxxxx",
      "name":"delete",
      "webUrl":https://msit.powerbi.com/reports/xxxxxxxxxx,
   }
}

  • 取得embed url與Access Token後,便可以依照PowerBI文件中 (https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-integrate-a-power-bi-tile-or-report/#integrate-a-power-bi-tile) Embed a Power BI report into an app 一節描述的方式將報表或Dashboard整合到app中。
  • 沒有留言:

    Blog Archive

    About Me