如何使用 Python 客户端正确验证 Kusto?

How to properly authenticate Kusto using a Python client?

我正在尝试测试我的节点和 Azure 数据资源管理器 (ADX/Kusto) 之间的连接。我正在考虑使用 python 脚本在 Kusto 上创建一个 table。

请注意,我对这些都不是很熟悉,因此下面是详细步骤。

我在 Microsoft 文档上关注此 quickstart guide

生成应用程序 ID 和密钥

使用应用程序注册服务:

  1. 创建新注册(名为 kusto 测试):

  2. 创建客户端密钥:

创建 Kusto 数据库

从集群中,从 UI(称为 kusto-test)

创建一个数据库

授权

在 ADX 集群上 > 访问控制 (IAM) > 添加角色分配。

Python 脚本

from azure.kusto.data.request import KustoClient, KustoConnectionStringBuilder
from azure.kusto.data.exceptions import KustoServiceError
from azure.kusto.data.helpers import dataframe_from_result_table

KUSTO_DATABASE = "kusto-test"
CLUSTER = "https://mynode.myregion.kusto.windows.net"

CLIENT_ID = "KUSTO_TEST_APP_ID" # From image above
CLIENT_SECRET = "KUSTO_TEST_PASS" # From image above

AUTHORITY_ID = "<insert here your tenant id>" #Got from https://login.windows.net/<YourDomain>/.well-known/openid-configuration/

KCSB_DATA = KustoConnectionStringBuilder.with_aad_application_key_authentication(
    CLUSTER, CLIENT_ID, CLIENT_SECRET, AUTHORITY_ID
)


KUSTO_CLIENT = KustoClient(KCSB_DATA)
CREATE_TABLE_COMMAND = ".create table StormEvents (StartTime: datetime, EndTime: datetime, EpisodeId: int, EventId: int, State: string, EventType: string, InjuriesDirect: int, InjuriesIndirect: int, DeathsDirect: int, DeathsIndirect: int, DamageProperty: int, DamageCrops: int, Source: string, BeginLocation: string, EndLocation: string, BeginLat: real, BeginLon: real, EndLat: real, EndLon: real, EpisodeNarrative: string, EventNarrative: string, StormSummary: dynamic)"

RESPONSE = KUSTO_CLIENT.execute_mgmt(KUSTO_DATABASE, CREATE_TABLE_COMMAND)

dataframe_from_result_table(RESPONSE.primary_results[0])

预计:

实际:

azure.kusto.data.exceptions.KustoServiceError: (KustoServiceError(...), [{u'error': {u'code': u'Forbidden', u'@permanent': True, u'@message': u"Principal '....' is not authorized to access database 'kusto-test'.", ...}, u'message': u'Caller is not authorized to perform this action', u'@type': u'Kusto.DataNode.Exceptions.UnauthorizedDatabaseAccessException'}}])

在 Azure 门户中添加所有者 "access control" 仅向该实体提供管理资源的权限(也称为 'control plane'),不适用于数据库本身的权限(也称为 'data plane')。

要提供该应用程序在数据平面中操作的权限,例如 运行 查询、创建表等,您需要在适用的数据库 "Permissions" 部分中授予它权限:

目前我最喜欢的一个方案是连接AZ Cli认证:

from azure.kusto.data import KustoClient, KustoConnectionStringBuilder
kcsb = KustoConnectionStringBuilder.with_az_cli_authentication(KUSTO_URI)
client = KustoClient(kcsb)

准备好在 3 行代码中隆隆作响。如果您尚未使用 AD 凭据登录,它会提示您这样做,打开 Web 浏览器进行登录。在我的情况下,只有软件开发人员/数据科学家需要使用 python 访问 Kusto。他们大多具有已通过资源组继承的权限。