Power BI 活动日志 REST API 获取访问令牌

时间:2021-02-21 01:24:56

标签: python azure powerbi azure-api-apps powerbi-api

试图从 Power BI Rest API 中提取活动日志时,我一直在发疯。我可以使用 Microsoft 的这种“尝试”方法来完成 https://docs.microsoft.com/en-us/rest/api/power-bi/admin/getactivityevents

我必须登录才能使用此工具,然后我会获得一个有效期为 1 小时的不记名 JWT 令牌,可以在脚本内的后续 get 请求的标头中使用。但是令牌会在 1 小时后过期,我必须重新登录才能获取新令牌并更新我的脚本。我试图在每次到期时检索 JWT 令牌,而无需通过 GUI 登录。这基本上是自动从 Power BI 获取日志以发送到安全应用程序进行分析。在 Azure/Power BI 方面,我已使用此链接 https://dev.powerbi.com/Apps 注册了本机应用程序。在 Azure 应用注册中,我已授予该应用所有 API 权限。

我有一些使用 adal 库的示例 python 代码,我想在这里工作。我想 Powershell 解决方案也是可以接受的,但我更喜欢使用 python。

import adal
import requests
import json
import pandas


authority_url = 'https://login.windows.net/common'
resource_url = 'https://analysis.windows.net/powerbi/api'
client_id = 'my client ID'
client_secret = 'my client secret'
context = adal.AuthenticationContext(authority=authority_url,
                                     validate_authority=True,
                                     api_version=None)

# get JWT access token without having to log in
token = context.acquire_token_with_client_credentials(resource_url, client_id, client_secret)

access_token = token.get('accessToken')
logs_request_url = "https://api.powerbi.com/v1.0/myorg/admin/activityevents?startDateTime=%272021-02-20T00%3A00%3A00.000Z%27&endDateTime=%272021-02-20T23%3A59%3A59.000Z%27"

header = {'Authorization': f'Bearer {access_token}','Content-Type': 'application/json'}
response = requests.get(url=logs_request_url, headers=header).content
logs_request = json.loads(response)
# Power BI Activity Logs
print(logs_request)

这段代码让我得到一个空的响应。如果我粘贴使用“尝试”工具登录时生成的 access_token ,它就可以工作。如果可能,我试图避免手动登录,因为此脚本将作为计划任务运行。我会很感激这方面的任何帮助,因为我正在疯狂地尝试让它工作。

1 个答案:

答案 0 :(得分:0)

我看到您已授予应用所需的权限。

在使用 API 之前,您需要在 Power Bi 租户级别启用以下设置(允许服务主体使用只读 Power BI 管理 API):

  • 登录 Power BI 管理门户。

enter image description here

  • 访问租户设置。

  • 在 Admin API 设置下,您将看到 Allow service principals to 使用只读 Power BI 管理 API。

enter image description here

  • 启用上述设置。

您可以参考这篇文章了解详细说明。 :https://docs.microsoft.com/en-us/power-bi/admin/read-only-apis-service-principal-authentication