python - API Power BI 获取 token 但获取请求获取响应 401

标签 python adal

我已经在 Azure 中注册了一个应用程序来访问 PBI(使用 MFA);

应用详情:

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

我可以获得 token ,但是当尝试运行获取请求时,我收到错误 401。

import adal
import requests


authority_url = 'https://login.windows.net/<tennantID>'
resource_url = 'https://analysis.windows.net/powerbi/api'
target_url = 'https://api.powerbi.com/v1.0/myorg/groups/<groupID>/datasets'

client_id = '<applicationID>'
secret= '<clientsecretID>'

context = adal.AuthenticationContext(authority=authority_url,
                                     validate_authority=True,
                                     api_version=None)

token = context.acquire_token_with_client_credentials(resource=resource_url,
                                                     client_id=client_id,
                                                     client_secret=secret)

access_token = token.get('accessToken')

#print(access_token)


header = {'Authorization': f'Bearer {access_token}'}
#print(header)
r = requests.get(url=target_url, headers=header)
r

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

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

最佳答案

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

先决条件

  • 一个组织事件目录和一个全局管理员
  • PowerBI Pro 许可证(您可以免费获得一个用于试用)
  • 您 AD 中同时登录到 Power BI 的用户

  • 创建应用程序

您需要创建一个应用程序,请按照本教程进行操作:https://learn.microsoft.com/en-us/power-bi/developer/register-app .确保保存应用程序 secret 和应用程序 ID。

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

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

  • 生成访问 token

首先,您需要生成一个访问 token ,用于在与 API 的进一步通信中验证您自己的身份。

端点:https://login.microsoftonline.com/common/oauth2/token 方法:POST 数据:

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_IDAPPLICATION_SECRET 替换为您在 AAD 中创建应用程序后获得的应用程序 ID 和密码。将 USER_IDUSER_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'}

获得 token 后,您就可以继续调用 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)

关于python - API Power BI 获取 token 但获取请求获取响应 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305847/

相关文章:

c# - ADAL 身份验证出错

java - 用于访问 token 的 ADAL java 库不返回组和角色

azure - 微软图形API : Insufficient privileges to complete the operation

python - python的pandas插件在canopy环境中不排序?

python - 获取尚未在 Python 中返回的(OS)命令的输出

python - 如何在python中制作固定大小的格式化字符串?

adal - 无法使用 adal.js 更新 token

node.js - Passport-azure-ad,它是否解析并验证 token ?

python - python在哪里寻找ctypes.cdll.<name>在windows上打开的dll?

python - 从 tomcat .dbx 文件迁移数据