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

Python API Power BI获取令牌但获取请求获取响应401,python,adal,Python,Adal,我已经在Azure中注册了一个应用程序来访问PBI(使用MFA) 应用程序详细信息: 本机应用程序(移动桌面) API权限 Azure Active Directory图表(1)用户。读取 Power Bi服务(1)DataSet.ReadWrite.All 我可以获取令牌,但当尝试运行get请求时,我得到错误401 import adal import requests authority_url = 'https://login.windows.net/<tennantID

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

应用程序详细信息:

  • 本机应用程序(移动桌面)
  • API权限
    • Azure Active Directory图表(1)用户。读取
    • Power Bi服务(1)DataSet.ReadWrite.All
我可以获取令牌,但当尝试运行get请求时,我得到错误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
导入adal
导入请求
当局https://login.windows.net/'
资源https://analysis.windows.net/powerbi/api'
目标https://api.powerbi.com/v1.0/myorg/groups//datasets'

client_id='/datasets

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

先决条件

  • 一个组织的Active Directory和一个全局管理员
  • PowerBI Pro许可证(您可以免费获得一个,供试用)
  • 您的广告中同时登录到Power BI的用户

  • 创建应用程序

您需要创建一个应用程序,请遵循以下教程:。确保保存应用程序机密和应用程序id

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

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

  • 生成访问令牌

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

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

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
用在AAD中创建应用程序后获得的应用程序ID和机密替换应用程序ID应用程序机密。用主用户的登录名/密码替换用户ID用户密码。剩下的就这样吧

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

{'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'}
一旦获得了令牌,就可以继续进行PowerBIAPI调用了

张贴我使用过的示例代码

"""
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)

这肯定是不对的,如果您为应用程序的服务主体提供了对工作区的访问,那么您不应该需要用户id和密码。这就像是手动登录用户一样。也就是说,它可以工作,但对于服务访问目的来说毫无意义。