简体   繁体   English

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

[英]API Power BI Get token but get request get response 401

I have registered an APP in Azure to access PBI (with MFA); 我已经在Azure中注册了一个APP以访问PBI(通过MFA);

APP details: APP详细信息:

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

I can get the token but when try to run a get request I get error 401. 我可以获取令牌,但是当尝试运行获取请求时,出现错误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

I expect to get a list of datasets on the group but getting error 401 我希望获得组上的数据集列表,但会收到错误401

HTTPError: 401 Client Error: Unauthorized for url: https://api.powerbi.com/v1.0/myorg/groups/ /datasets HTTPError:401客户端错误:未经授权的URL: https : //api.powerbi.com/v1.0/myorg/groups/ / datasets

Here are the steps to access powerBI reporting data from python 以下是从python访问powerBI报告数据的步骤

Pre-requisite 前提条件

  • an Organizational Active Directory, and a global admin on it 组织活动目录及其上的全局管理员
  • a PowerBI Pro Licence (you can get one for free, for trial) PowerBI Pro许可证(您可以免费获得一个试用版)
  • a user in your AD that is also logged in to Power BI 您AD中也已登录Power BI的用户

  • Create an Application 创建一个应用程序

You need to create an application, follow this tutorial: https://docs.microsoft.com/en-us/power-bi/developer/register-app . 您需要创建一个应用程序,然后遵循本教程: https : //docs.microsoft.com/zh-cn/power-bi/developer/register-app Make sure you save the application secret and application id. 确保保存了应用程序密码和应用程​​序ID。

Make sure the permissions are all correct (remember you have to click "Save" then "Grant permissions" when modifying the permission in Azure AD). 确保权限全部正确(记住在Azure AD中修改权限时必须单击“保存”,然后单击“授予权限”)。

  • Ensure power bi report exist for the link and it is published. 确保该链接存在power bi报告并已发布。

  • Generating an Access Token 生成访问令牌

First thing first, you need to generate an access token, that will be used to authenticate yourself in further communication with the API. 首先,您需要生成一个访问令牌,该令牌将用于与API进行进一步通信时对自己进行身份验证。

Endpoint: https://login.microsoftonline.com/common/oauth2/token Method: POST Data: 端点: https://login.microsoftonline.com/common/oauth2/token Method: POST Data: : 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

replace APPLICATION_ID , APPLICATION_SECRET with the application id and secret you got after creating the app in AAD. 将您在AAD中创建应用后获得的应用ID和密码替换为APPLICATION_IDAPPLICATION_SECRET Replace USER_ID and USER_PASSWORD with the login/password for the master user. 用主用户的登录名/密码替换USER_IDUSER_PASSWORD Leave the rest as is. 其余部分保持原样。

If successful, you should obtain a response similar to: 如果成功,您应该获得类似于以下内容的响应:

{'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'}

Once you have obtained the token , you are good to proceed with PowerBi api calls. 获得令牌后,可以继续进行PowerBi api调用。

posting a sample code which i have used. 发布我使用过的示例代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM