在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
- 首先,回到https://manage.windowsazure.com ;手動註冊一個Native App
- Redirect URL可以隨意給一個合法的URL即可,例如http://localhost
- 註冊完成後,新增PowerBI Application
- 接著給予相對應的權限
- 記住ClientID
- 記下Tenant ID
- 接著,我們需要一隻程式幫我們抓到所有PowerBI上的相關報表、Dashboard…etc
- 開啟一個Visual Studio專案,這個專案也可以是我們到時要整合的Web App;加入以下的NUGet Package
- 加入以下程式碼:
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,
}
}
沒有留言:
張貼留言