API Power BI获取令牌,但获取请求获取响应401

时间:2019-08-01 09:26:54

标签: python adal

我已经在Azure中注册了一个APP以访问PBI(通过MFA);

APP详细信息:

  • 本机应用程序(移动桌面)
  • API权限
    • Azure Active Directory图(1)User.Read
    • Power Bi服务(1)DataSet.ReadWrite.All

我可以获取令牌,但是当尝试运行获取请求时,出现错误401。

if (!empty($buy_now_persistent_cart['cart'])) {
   WC()->cart->empty_cart();
   foreach($buy_now_persistent_cart['cart'] as $item){
      WC()->cart->add_to_cart($item['product_id'], $item['quantity']);
   }
}

我希望获得组中的数据集列表,但会收到错误401

HTTPError:401客户端错误:未经授权的url:https://api.powerbi.com/v1.0/myorg/groups/ /数据集

1 个答案:

答案 0 :(得分:2)

以下是从python访问powerBI报告数据的步骤

先决条件

  • 组织活动目录及其上的全局管理员
  • PowerBI Pro许可证(您可以免费获得试用版)
  • 您AD中的一个用户也已登录Power BI

  • 创建应用程序

您需要创建一个应用程序,请遵循本教程:https://docs.microsoft.com/en-us/power-bi/developer/register-app。确保保存了应用程序密码和应用程​​序ID。

确保所有权限都是正确的(记住在Azure AD中修改权限时必须先单击“保存”,然后单击“授予权限”。)

  • 确保该链接存在power bi报告并已发布。

  • 生成访问令牌

首先,您需要生成一个访问令牌,该令牌将用于与API进行进一步通信时对自己进行身份验证。

端点:https://login.microsoftonline.com/common/oauth2/token Method: POST Data:

grant_type: password
scope: openid
resource: https://analysis.windows.net/powerbi/api
client_id: APPLICATION_ID
client_secret: APPLICATION_SECRET
username: USER_ID
password: USER_PASSWORD
APPLICATION_ID APPLICATION_SECRET 替换为在AAD中创建应用后获得的应用ID和密码。将 USER_ID USER_PASSWORD 替换为主用户的登录名/密码。其余的保持不变。

如果成功,您应该获得类似于以下内容的响应:

{'access_token': 'eyJ0...ubUA',
 'expires_in': '3599',
 'expires_on': '1515663724',
 'ext_expires_in': '0',
 'id_token': 'eyJ0A...MCJ9.',
 'not_before': '1515659824',
 'refresh_token': 'AQABAA...hsSvCAA',
 'resource': 'https://analysis.windows.net/powerbi/api',
 'scope': 'Capacity.Read.All Capacity.ReadWrite.All Content.Create Dashboard.Read.All Dashboard.ReadWrite.All Data.Alter_Any Dataset.Read.All Dataset.ReadWrite.All Group.Read Group.Read.All Metadata.View_Any Report.Read.All Report.ReadWrite.All Tenant.Read.All Workspace.Read.All Workspace.ReadWrite.All',
 'token_type': 'Bearer'}

获得令牌后,可以继续进行PowerBi api调用了。

发布我已使用的示例代码。

"""
Simple example code to communicate with Power BI REST API. Hope it helps.


"""
import requests


# Configuration goes here:
RESOURCE = "https://analysis.windows.net/powerbi/api"  # Don't change that.
APPLICATION_ID = "abcdef-abcdef-abcdef-abcdef"  # The ID of the application in Active Directory
APPLICATION_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxx"  # A valid key for that application in Active Directory

USER_ID = "emmanuel@your_company.com"  # A user that has access to PowerBI and the application
USER_PASSWORD = "password"  # The password for that user

GROUP_ID = 'xxxxxxxxxxx'  # The id of the workspace containing the report you want to embed
REPORT_ID = 'xxxxxxxxxxxxxx'  # The id of the report you want to embed


def get_access_token(application_id, application_secret, user_id, user_password):
    data = {
        'grant_type': 'password',
        'scope': 'openid',
        'resource': "https://analysis.windows.net/powerbi/api",
        'client_id': application_id,
        'client_secret': application_secret,
        'username': user_id,
        'password': user_password
    }
    token = requests.post("https://login.microsoftonline.com/common/oauth2/token", data=data)
    assert token.status_code == 200, "Fail to retrieve token: {}".format(token.text)
    print("Got access token: ")
    print(token.json())
    return token.json()['access_token']


def make_headers(application_id, application_secret, user_id, user_password):
    return {
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': "Bearer {}".format(get_access_token(application_id, application_secret, user_id, user_password))
    }


def get_embed_token_report(application_id, application_secret, user_id, user_password, group_id, report_id):
    endpoint = "https://api.powerbi.com/v1.0/myorg/groups/{}/reports/{}/GenerateToken".format(group_id, report_id)
    headers = make_headers(application_id, application_secret, user_id, user_password)
    res = requests.post(endpoint, headers=headers, json={"accessLevel": "View"})
    return res.json()['token']


def get_groups(application_id, application_secret, user_id, user_password):
    endpoint = "https://api.powerbi.com/v1.0/myorg/groups"
    headers = make_headers(application_id, application_secret, user_id, user_password)
    return requests.get(endpoint, headers=headers).json()


def get_dashboards(application_id, application_secret, user_id, user_password, group_id):
    endpoint = "https://api.powerbi.com/v1.0/myorg/groups/{}/dashboards".format(group_id)
    headers = make_headers(application_id, application_secret, user_id, user_password)
    return requests.get(endpoint, headers=headers).json()


def get_reports(application_id, application_secret, user_id, user_password, group_id):
    endpoint = "https://api.powerbi.com/v1.0/myorg/groups/{}/reports".format(group_id)
    headers = make_headers(application_id, application_secret, user_id, user_password)
    return requests.get(endpoint, headers=headers).json()


# ex:
# get_embed_token_report(APPLICATION_ID, APPLICATION_SECRET, USER_ID, USER_PASSWORD, GROUP_ID, REPORT_ID)