You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python调用MS Fabric API时服务主体令牌权限未授予问题排查

问题描述

我正在VSCode中使用Python尝试连接Microsoft Fabric的OneLake API,已完成以下操作:

  • 在Azure中注册应用并配置了对应的API权限;
  • 为服务主体创建了密钥;
  • 使用azure.identity库编写函数获取访问令牌,令牌获取成功:
from azure.identity import ClientSecretCredential, AuthenticationRequiredError

def get_access_token(app_id, client_secret, directory_id):
    try:
        # 创建ClientSecretCredential实例
        credential = ClientSecretCredential(
            client_id=app_id,
            client_secret=client_secret,
            tenant_id=directory_id
            #scope="https://storage.azure.com/.default"
        )

        # 获取访问令牌
        token = credential.get_token("https://storage.azure.com/.default").token

        return token, credential

    except AuthenticationRequiredError as e:
        print("身份验证失败,请检查凭据。")
        raise e

    except Exception as e:
        print("获取访问令牌时出错:")
        print(str(e))
        raise e
    
access_token, credential = get_access_token(app_id, client_secret, directory_id)
  • 将该服务主体添加为Fabric工作区的管理员。

但调用以下函数检查连接时返回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("OneLake连接成功。")
        else:
            print("OneLake连接失败。状态码:", response.status_code)

    except requests.exceptions.RequestException as e:
        print("检查连接时出错:", str(e))

# 假设access_token已定义且有效
check_connection_with_onelake(access_token)
问题分析与解决方案

1. 令牌Scope错误

OneLake API对应的正确scope不是https://storage.azure.com/.default,而是https://onelake.dfs.fabric.microsoft.com/.default。你当前获取的令牌是针对Azure Storage的,无法通过OneLake的身份验证。

修改get_access_token函数中的令牌请求scope:

token = credential.get_token("https://onelake.dfs.fabric.microsoft.com/.default").token

2. API请求方式与路径问题

你使用PUT请求创建文件,但存在两个问题:

  • 仅发送PUT请求但未携带文件内容,会导致400错误;
  • 路径格式需要确认:如果sample是要创建的文件名,需要确保路径指向有效位置,且请求中包含文件数据。

建议先改用GET请求测试基础权限,比如访问Files容器根目录:

base_url = "https://onelake.dfs.fabric.microsoft.com/9c3ffd43-b537-4ca2-b9ba-0c59d0094033/Files?resource=container"
response = requests.get(base_url, headers=token_headers)

如果要创建文件,需在PUT请求中添加内容:

response = requests.put(base_url, headers=token_headers, data="测试内容")

3. 权限配置验证

确保Azure应用注册中添加的是OneLake专属API权限,而非Azure Storage权限。需要添加https://onelake.dfs.fabric.microsoft.com下的权限(如Files.ReadWrite.All),并且已完成管理员同意流程。

仅将服务主体设为工作区管理员不足以完成授权,必须确认应用注册的权限已正确配置并获得管理员同意。

内容的提问来源于stack exchange,提问作者Jon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:24:59