未使用 Python 在 MS Fabric API 中为服务主体令牌授予身份验证

问题描述 投票:0回答:0

我正在尝试在 VScode 中使用 Python 连接到 Microsoft Fabric 中的 OneLake API。

到目前为止我已经

  1. 使用这些 API 权限在 Azure 中注册了一个应用程序

  1. 然后为我的服务主体创建一个秘密
  2. 然后我尝试使用 azure.identity 通过此函数获取令牌:
from azure.identity import ClientSecretCredential, AuthenticationRequiredError

def get_access_token(app_id, client_secret, directory_id):
    try:
        # Create the ClientSecretCredential using the provided credentials
        credential = ClientSecretCredential(
            client_id=app_id,
            client_secret=client_secret,
            tenant_id=directory_id
            #scope="https://storage.azure.com/.default"
        )

        # Use the credential to get the access token
        token = credential.get_token("https://storage.azure.com/.default").token

        return token, credential

    except AuthenticationRequiredError as e:
        print("Authentication failed. Please check your credentials.")
        raise e

    except Exception as e:
        print("An error occurred while getting the access token:")
        print(str(e))
        raise e
    
access_token, credential = get_access_token(app_id, client_secret, directory_id)

看来我得到了令牌。但权限、范围或访问权限有问题。因为当我运行此函数来检查连接时,我收到状态代码 400

def check_connection_with_onelake(access_token):
    base_url = "https://onelake.dfs.fabric.microsoft.com/9c3ffd43-b537-4ca2-b9ba-0c59d0094033/Files/sample?resource=file" 
    token_headers = {
        "Authorization": "Bearer " + access_token
    }

    try:
        response = requests.put(base_url, headers=token_headers)

        if response.status_code == 200:
            print("Connection with OneLake is successful.")
        else:
            print("Failed to connect with OneLake. Status code:", response.status_code)

    except requests.exceptions.RequestException as e:
        print("An error occurred while checking the connection:", str(e))

# Assuming 'access_token' is already defined and contains a valid access token
check_connection_with_onelake(access_token)
  1. 我还以管理员身份将应用程序的服务主体添加到 Fabric 工作区中的用户

我在哪里缺少访问权限以及如何授予正确的访问权限?

参考资料: https://learn.microsoft.com/en-us/fabric/onelake/onelake-access-api https://amitchandak.medium.com/on-premise-python-code-to-local-sql-server-data-to-microsoft-fabric-lakehouse-using-token-d15b8795e349

python azure token fabric azure-service-principal
© www.soinside.com 2019 - 2024. All rights reserved.