适用范围:
Azure CLI ml 扩展 v2(最新版)
Python SDK azure-ai-ml v2(最新版)
本文介绍如何对客户端进行身份验证,以便在联机终结点上执行控制平面和数据平面操作。
控制平面操作可控制终结点并对其进行更改。 控制平面操作包括在联机终结点和联机部署上进行的创建、读取、更新和删除 (CRUD) 操作。
数据平面操作使用数据与联机终结点交互,而无需更改终结点。 例如,数据平面操作可能包括向联机终结点发送评分请求并获取响应。
先决条件
- Microsoft Entra ID 中的用户标识。 有关创建用户标识的信息,请参阅 “设置身份验证”。 稍后需要标识 ID。
-
控制平面和数据平面所需的 RBAC 角色:在工作区范围内,将以下角色之一分配给用户标识:
-
AzureML 数据科学家 (内置)— 包括对终结点和打分的 CRUD 操作权限。 请参阅 AzureML 数据科学家角色。
-
所有者 或 参与者 - 对管理终结点的完全访问权限。
- 具有
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/*操作的自定义角色。
- (可选) Azure 机器学习工作区连接机密读取者 - 仅当需要从工作区连接访问机密时才是必需的。
验证设置
运行此代码片段以验证凭据和 RBAC 权限是否已正确配置:
az login
az ml online-endpoint list --resource-group <RESOURCE_GROUP> --workspace-name <WORKSPACE_NAME>
预期输出:终结点的 JSON 数组(如果尚不存在终结点,则为空 [] )。
参考: az ml online-endpoint list
from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential
subscription_id = "<SUBSCRIPTION_ID>"
resource_group = "<RESOURCE_GROUP>"
workspace = "<WORKSPACE_NAME>"
ml_client = MLClient(
DefaultAzureCredential(), subscription_id, resource_group, workspace
)
# List existing endpoints to verify access
endpoints = ml_client.online_endpoints.list()
print("Existing endpoints:", [ep.name for ep in endpoints])
预期输出:终结点名称列表(如果尚不存在终结点,则为空列表 [] )。
参考: MLClient、 DefaultAzureCredential
# First, get a token
export CONTROL_PLANE_TOKEN=$(az account get-access-token \
--resource https://management.chinacloudapi.cn \
--query accessToken -o tsv)
# List endpoints
curl -s -X GET \
"https://management.chinacloudapi.cn/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/Microsoft.MachineLearningServices/workspaces/<WORKSPACE_NAME>/onlineEndpoints?api-version=2024-04-01" \
-H "Authorization: Bearer $CONTROL_PLANE_TOKEN" \
-H "Content-Type: application/json"
预期输出:一个包含value端点的数组的JSON响应。
向标识分配权限
如果已分配所需的 RBAC 角色(如 先决条件中所示),请跳到 “创建终结点”。 本部分提供有关自定义角色创建的详细信息(如果需要)。
查看内置角色详细信息
AzureML Data Scientist
内置角色包括以下控制平面 RBAC 操作:
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/write
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/delete
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/read
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/token/action
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/listKeys/action
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/regenerateKeys/action
此数据平面 RBAC 操作:
Microsoft.MachineLearningServices/workspaces/onlineEndpoints/score/action
Azure Machine Learning Workspace Connection Secrets Reader内置角色包括:
Microsoft.MachineLearningServices/workspaces/connections/listsecrets/action
Microsoft.MachineLearningServices/workspaces/metadata/secrets/read
(可选)创建自定义角色
如果使用内置角色或其他预制自定义角色,可以跳过此步骤。
通过创建角色的 JSON 定义来定义自定义角色的范围和操作。 例如,以下角色定义 custom-role-for-control-plane.json允许用户对指定工作区中的在线端点执行 CRUD 操作。
{
"Name": "Custom role for control plane operations - online endpoint",
"IsCustom": true,
"Description": "Can CRUD against online endpoints.",
"Actions": [
"Microsoft.MachineLearningServices/workspaces/onlineEndpoints/write",
"Microsoft.MachineLearningServices/workspaces/onlineEndpoints/delete",
"Microsoft.MachineLearningServices/workspaces/onlineEndpoints/read",
"Microsoft.MachineLearningServices/workspaces/onlineEndpoints/token/action",
"Microsoft.MachineLearningServices/workspaces/onlineEndpoints/listKeys/action",
"Microsoft.MachineLearningServices/workspaces/onlineEndpoints/regenerateKeys/action"
],
"NotActions": [
],
"AssignableScopes": [
"/subscriptions/<subscriptionID>/resourcegroups/<resourceGroupName>"
]
}
以下角色定义 custom-role-for-scoring.json允许用户将评分请求发送到指定工作区中的联机终结点。
{
"Name": "Custom role for scoring - online endpoint",
"IsCustom": true,
"Description": "Can score against online endpoints.",
"Actions": [
"Microsoft.MachineLearningServices/workspaces/onlineEndpoints/*/action"
],
"NotActions": [
],
"AssignableScopes": [
"/subscriptions/<subscriptionID>/resourcegroups/<resourceGroupName>"
]
}
使用 JSON 定义创建自定义角色:
az role definition create --role-definition custom-role-for-control-plane.json --subscription <subscriptionID>
az role definition create --role-definition custom-role-for-scoring.json --subscription <subscriptionID>
注意
若要创建自定义角色,需要具有下面三个角色之一:
- 所有者
- 用户访问管理员
- 具有
Microsoft.Authorization/roleDefinitions/write 权限的自定义角色(用于创建/更新/删除自定义角色)和 Microsoft.Authorization/roleDefinitions/read 权限(查看自定义角色)。
若要详细了解如何创建自定义角色,请参阅 Azure 自定义角色。
验证角色定义:
az role definition list --custom-role-only -o table
az role definition list -n "Custom role for control plane operations - online endpoint"
az role definition list -n "Custom role for scoring - online endpoint"
export role_definition_id1=`(az role definition list -n "Custom role for control plane operations - online endpoint" --query "[0].id" | tr -d '"')`
export role_definition_id2=`(az role definition list -n "Custom role for scoring - online endpoint" --query "[0].id" | tr -d '"')`
将角色分配给标识
如果使用 AzureML Data Scientist 内置角色,请使用以下代码将角色分配给用户标识。
az role assignment create --assignee <identityID> --role "AzureML Data Scientist" --scope /subscriptions/<subscriptionID>/resourcegroups/<resourceGroupName>/providers/Microsoft.MachineLearningServices/workspaces/<workspaceName>
(可选)如果使用 Azure Machine Learning Workspace Connection Secrets Reader 内置角色,请使用以下代码将角色分配给用户标识。
az role assignment create --assignee <identityID> --role "Azure Machine Learning Workspace Connection Secrets Reader" --scope /subscriptions/<subscriptionID>/resourcegroups/<resourceGroupName>/providers/Microsoft.MachineLearningServices/workspaces/<workspaceName>
如果使用自定义角色,请使用以下代码将角色分配给用户标识。
az role assignment create --assignee <identityID> --role "Custom role for control plane operations - online endpoint" --scope /subscriptions/<subscriptionID>/resourcegroups/<resourceGroupName>/providers/Microsoft.MachineLearningServices/workspaces/<workspaceName>
az role assignment create --assignee <identityID> --role "Custom role for scoring - online endpoint" --scope /subscriptions/<subscriptionID>/resourcegroups/<resourceGroupName>/providers/Microsoft.MachineLearningServices/workspaces/<workspaceName>
注意
若要将自定义角色分配给用户标识,需要具有下面三个角色之一:
- 所有者
- 用户访问管理员
- 允许
Microsoft.Authorization/roleAssignments/write权限(分配自定义角色)和Microsoft.Authorization/roleAssignments/read(查看角色分配)的自定义角色。
有关 Azure 角色及其权限的详细信息,请参阅 Azure 角色 , 并使用 Azure 门户分配 Azure 角色。
确认角色分配:
az role assignment list --scope /subscriptions/<subscriptionID>/resourcegroups/<resourceGroupName>/providers/Microsoft.MachineLearningServices/workspaces/<workspaceName>
获取用于控制平面操作的 Microsoft Entra 令牌
如果计划通过直接使用令牌的 REST API 来执行控制平面操作,请完成此步骤。
如果计划将其他方法(如 Azure CLI 与 ml 扩展 v2、Python SDK v2 或 Azure 机器学习工作室)配合使用,则无需手动获取 Microsoft Entra 令牌。 您的用户身份将在登录时进行身份验证,系统将自动检索并为您传递令牌。
可以从 Azure 资源终结点检索用于控制平面操作的 Microsoft Entra 令牌:https://management.chinacloudapi.cn
登录 Azure。
az login
如果要使用特定标识,请通过以下代码使用标识进行登录:
az login --identity --username <identityID>
使用此上下文获取令牌:
export CONTROL_PLANE_TOKEN=$(az account get-access-token \
--resource https://management.chinacloudapi.cn \
--query accessToken -o tsv)
参考: az login、 az account get-access-token
from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential
try:
credential = DefaultAzureCredential()
# Check whether given credential can get token.
access_token = credential.get_token("https://management.chinacloudapi.cn/.default")
print(access_token)
except Exception as ex:
# Fall back to InteractiveBrowserCredential in case DefaultAzureCredential doesn't work.
# This will open a browser page.
credential = InteractiveBrowserCredential()
参考: DefaultAzureCredential、 InteractiveBrowserCredential
有关详细信息,请参阅 使用 Azure 标识客户端库获取令牌。
通过 Azure 虚拟机
可以根据 Azure VM 的托管标识(当 VM 启用托管标识时)获取令牌。
若要获取 Microsoft Entra 令牌 (aad_token) 来在 Azure VM 上进行控制平面操作,请将请求提交到 Azure 资源终结点 的 management.chinacloudapi.cn (IMDS) 终结点:
export CONTROL_PLANE_TOKEN=$(curl -s \
'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.chinacloudapi.cn%2F' \
-H Metadata:true | jq -r '.access_token')
提示
该 jq 实用工具用于从 JSON 输出中提取令牌。 但是,可以使用任何合适的工具来实现此目的。
若要详细了解如何基于托管标识获取令牌,请参阅使用 HTTP 获取令牌。
从计算实例
如果使用 Azure 机器学习工作区的计算实例,则可以获取令牌。 要获取令牌,你必须将计算实例托管标识的客户端 ID 和机密传递到在计算实例本地配置的托管系统标识 (MSI) 终结点。 可以从环境变量 MSI_ENDPOINT、DEFAULT_IDENTITY_CLIENT_ID 和 MSI_SECRET 分别获取 MSI 终结点、客户端 ID 和机密。 如果为计算实例启用托管标识,会自动设置这些变量。
从工作区的计算实例获取 Azure 资源终结点 management.chinacloudapi.cn 的令牌:
export CONTROL_PLANE_TOKEN=$(curl -s \
"${MSI_ENDPOINT}?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.chinacloudapi.cn%2F&clientid=${DEFAULT_IDENTITY_CLIENT_ID}" \
-H Metadata:true \
-H "Secret:$MSI_SECRET" | jq -r '.access_token')
工作室不会公开用于控制平面操作的 Microsoft Entra 令牌。
(可选)验证 Microsoft Entra 令牌的资源端点和客户端 ID
检索Microsoft Entra 令牌后,可以通过通过 management.chinacloudapi.cn 解码令牌来验证令牌是否适用于正确的 Azure 资源终结点()和正确的客户端 ID,这会返回包含以下信息的 JSON 响应:
{
"aud": "https://management.chinacloudapi.cn",
"oid": "<your-object-id>"
}
创建终结点
以下示例创建一个终结点,其终结点标识为系统分配的标识。 系统分配的标识是终结点托管标识的默认标识类型。 系统分配的标识会自动分配一些基本角色。 若要详细了解系统分配标识的角色分配,请参阅终结点标识的自动角色分配。
CLI 不要求显式提供控制平面令牌。 相反,CLI az login 命令会在登录期间对你进行身份验证,并且会自动检索并传递令牌。
创建名为 endpoint.yml的终结点定义 YAML 文件:
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
name: my-endpoint
auth_mode: aad_token
可以将auth_mode设置为key以进行密钥身份验证或设置为aml_token以进行Azure机器学习令牌身份验证。 此示例使用 aad_token 进行 Microsoft Entra 令牌身份验证。
创建终结点:
az ml online-endpoint create -f endpoint.yml
检查终结点的状态:
az ml online-endpoint show -n my-endpoint
如果要在创建终结点时替代 auth_mode(例如,替代为 aad_token),请运行以下代码:
az ml online-endpoint create -n my-endpoint --auth-mode aad_token
如果要更新现有终结点并指定 auth_mode (例如,如), aad_token请运行以下代码:
az ml online-endpoint update -n my-endpoint --set auth_mode=aad_token
参考: az ml online-endpoint create, az ml online-endpoint show, az ml online-endpoint update
Python SDK 不要求显式提供控制平面令牌。 相反,SDK MLClient 会在登录期间对你进行身份验证,系统会自动检索和传递令牌。
from azure.ai.ml import MLClient
from azure.ai.ml.entities import (
ManagedOnlineEndpoint,
ManagedOnlineDeployment,
Model,
Environment,
CodeConfiguration,
)
from azure.identity import DefaultAzureCredential
subscription_id = "<SUBSCRIPTION_ID>"
resource_group = "<RESOURCE_GROUP>"
workspace = "<WORKSPACE_NAME>"
ml_client = MLClient(
DefaultAzureCredential(), subscription_id, resource_group, workspace
)
endpoint = ManagedOnlineEndpoint(
name="my-endpoint",
description="this is a sample online endpoint",
auth_mode="aad_token",
tags={"foo": "bar"},
)
ml_client.online_endpoints.begin_create_or_update(endpoint).result()
可以将auth_mode替换为key以进行密钥身份验证,或替换为aml_token以进行Azure机器学习令牌身份验证。 示例使用aad_token进行Microsoft Entra令牌身份验证。
参考:MLClient、ManagedOnlineEndpoint、begin_create_or_update
REST API 调用不要求显式提供控制平面令牌。 使用之前检索到的控制平面令牌。
创建或更新终结点:
export SUBSCRIPTION_ID=<SUBSCRIPTION_ID>
export RESOURCE_GROUP=<RESOURCE_GROUP>
export WORKSPACE=<WORKSPACE_NAME>
export ENDPOINT_NAME=<ENDPOINT_NAME>
export LOCATION=<LOCATION_NAME>
export API_VERSION=2024-04-01
response=$(curl --location --request PUT \
"https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/$ENDPOINT_NAME?api-version=$API_VERSION" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $CONTROL_PLANE_TOKEN" \
--data-raw '{
"identity": {
"type": "systemAssigned"
},
"properties": {
"authMode": "AADToken"
},
"location": "'"$LOCATION"'"
}')
echo $response
可以将authMode替换为key以进行密钥身份验证,或替换为AMLToken以进行Azure机器学习令牌身份验证。 在此示例中,你使用 AADToken 进行 Microsoft Entra 令牌身份验证。
获取联机终结点的当前状态:
response=$(curl --location --request GET \
"https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/$ENDPOINT_NAME?api-version=$API_VERSION" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $CONTROL_PLANE_TOKEN")
echo $response
参考: 联机终结点 - 创建或更新、 联机终结点 - 获取
创建部署
若要创建部署,请参阅 使用联机终结点部署机器学习模型 ,或使用 REST 将模型部署为联机终结点。 为不同的身份验证模式创建部署的方式没有区别。
以下代码是关于如何创建部署的示例。 有关部署联机终结点的详细信息,请参阅 使用联机终结点(通过 CLI)部署机器学习模型。
创建名为 blue-deployment.yml的部署定义 YAML 文件:
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: blue
endpoint_name: my-aad-auth-endp1
model:
path: ../../model-1/model/
code_configuration:
code: ../../model-1/onlinescoring/
scoring_script: score.py
environment:
conda_file: ../../model-1/environment/conda.yml
image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu22.04:latest
instance_type: Standard_DS3_v2
instance_count: 1
使用 YAML 文件创建部署。 对于此示例,请将所有流量设置为新部署。
az ml online-deployment create -f blue-deployment.yml --all-traffic
参考: az ml online-deployment create
获取终结点的评分 URI
如果使用 az ml online-endpoint invoke 调用终结点,CLI 会自动解析评分 URI,因此无需手动检索它。
但是,如果需要用于其他工具(如 REST API 或自定义 HTTP 客户端)的评分 URI,可以使用以下命令检索它:
scoringUri=$(az ml online-endpoint show -n my-endpoint --query "scoring_uri")
参考: az ml online-endpoint show
如果计划使用 Python SDK 调用终结点,则无需显式获取评分 URI,因为 SDK 会为你提供评分 URI。 但是,仍可以使用 SDK 获取评分 URI,以便将其与其他通道(例如 REST API)一起使用。
scoring_uri = ml_client.online_endpoints.get(name=endpoint_name).scoring_uri
参考: OnlineEndpointOperations.get
export SUBSCRIPTION_ID=<SUBSCRIPTION_ID>
export RESOURCE_GROUP=<RESOURCE_GROUP>
export WORKSPACE=<WORKSPACE_NAME>
export ENDPOINT_NAME=<ENDPOINT_NAME>
export API_VERSION=2024-04-01
response=$(curl --location --request GET \
"https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/$ENDPOINT_NAME?api-version=$API_VERSION" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $CONTROL_PLANE_TOKEN")
scoringUri=$(echo $response | jq -r '.properties.scoringUri')
echo $response
echo $scoringUri
如果计划使用 Studio 调用终结点,则无需显式获取评分 URI,因为 Studio 会为你提供它。 但是,你仍然可以使用工作室来获取评分 URI,以便你可以将其与其他通道(例如 REST API)一起使用。
可以在终结点页面的“详细信息”选项卡上找到评分 URI。
获取数据平面操作的密钥或令牌
即使获取密钥或令牌的过程是控制平面操作,也可以对数据平面操作使用密钥或令牌。 换句话说,可以使用控制平面令牌获取稍后用于执行数据平面操作的密钥或令牌。
若要获取密钥或 Azure 机器学习令牌,请求它的用户身份需要为其分配相应的角色,如 控制平面操作的授权中所述。
用户标识不需要任何额外的角色来获取 Microsoft Entra 令牌。
如果计划使用 CLI 调用终结点,则无需显式获取数据平面操作的密钥或令牌,因为 CLI 会为你提供这些信息。 但是,仍然可以使用 CLI 来获取密钥或令牌,用于数据平面操作,这样可以与其他通道一起使用,例如 REST API。
若要获取数据平面操作的密钥或令牌,请使用 az ml online-endpoint get-credentials 命令。 此命令返回包含密钥、令牌和/或其他信息的 JSON 输出。
提示
在以下命令中,该 --query 参数用于从 JSON 输出中提取特定信息。 但是,可以将任何合适的工具用于该目的。
当终结点的 auth_mode 为 key
密钥在 primaryKey 和 secondaryKey 字段中返回。
export DATA_PLANE_TOKEN=$(az ml online-endpoint get-credentials -n $ENDPOINT_NAME -g $RESOURCE_GROUP -w $WORKSPACE_NAME -o tsv --query primaryKey)
export DATA_PLANE_TOKEN2=$(az ml online-endpoint get-credentials -n $ENDPOINT_NAME -g $RESOURCE_GROUP -w $WORKSPACE_NAME -o tsv --query secondaryKey)
当终结点的 auth_mode 为 aml_token
令牌在 accessToken 字段中返回。
令牌过期时间在 expiryTimeUtc 字段中返回。
令牌刷新时间在 refreshAfterTimeUtc 字段中返回。
export DATA_PLANE_TOKEN=$(az ml online-endpoint get-credentials -n $ENDPOINT_NAME -g $RESOURCE_GROUP -w $WORKSPACE_NAME -o tsv --query accessToken)
export EXPIRY_TIME_UTC=$(az ml online-endpoint get-credentials -n $ENDPOINT_NAME -g $RESOURCE_GROUP -w $WORKSPACE_NAME -o tsv --query expiryTimeUtc)
export REFRESH_AFTER_TIME_UTC=$(az ml online-endpoint get-credentials -n $ENDPOINT_NAME -g $RESOURCE_GROUP -w $WORKSPACE_NAME -o tsv --query refreshAfterTimeUtc)
当终结点的 auth_mode 为 aad_token
令牌在 accessToken 字段中返回。
令牌过期时间在 expiryTimeUtc 字段中返回。
export DATA_PLANE_TOKEN=$(az ml online-endpoint get-credentials -n $ENDPOINT_NAME -g $RESOURCE_GROUP -w $WORKSPACE_NAME -o tsv --query accessToken)
export EXPIRY_TIME_UTC=$(az ml online-endpoint get-credentials -n $ENDPOINT_NAME -g $RESOURCE_GROUP -w $WORKSPACE_NAME -o tsv --query expiryTimeUtc)
参考: az ml online-endpoint get-credentials
如果使用 SDK invoke() 的方法调用终结点,SDK 会自动处理身份验证,因此无需手动检索密钥或令牌。
但是,如果需要检索用于其他工具(如 REST API 或自定义 HTTP 客户端)的密钥或令牌,则可以在类中使用 OnlineEndpointOperations 方法。 此方法将返回包含密钥和令牌的对象。
当终结点的 auth_mode 为 key
密钥在 primary_key 和 secondary_key 字段中返回。
DATA_PLANE_TOKEN = ml_client.online_endpoints.get_keys(name=endpoint_name).primary_key
DATA_PLANE_TOKEN2 = ml_client.online_endpoints.get_keys(name=endpoint_name).secondary_key
当终结点的 auth_mode 为 aml_token
令牌在 access_token 字段中返回。
令牌过期时间在 expiry_time_utc 字段中返回。
令牌刷新时间在 refresh_after_time_utc 字段中返回。
DATA_PLANE_TOKEN = ml_client.online_endpoints.get_keys(name=endpoint_name).access_token
EXPIRY_TIME_UTC = ml_client.online_endpoints.get_keys(name=endpoint_name).expiry_time_utc
REFRESH_AFTER_TIME_UTC = ml_client.online_endpoints.get_keys(name=endpoint_name).refresh_after_time_utc
当终结点的 auth_mode 为 aad_token
令牌在 access_token 字段中返回。
令牌过期时间在 expiry_time_utc 字段中返回。
DATA_PLANE_TOKEN = ml_client.online_endpoints.get_keys(name=endpoint_name).access_token
EXPIRY_TIME_UTC = ml_client.online_endpoints.get_keys(name=endpoint_name).expiry_time_utc
参考: OnlineEndpointOperations.get_keys
有关详细信息,请参阅 使用 Azure 标识客户端库获取令牌。
若要获取数据平面操作的密钥或令牌,请选择正确的 API,具体取决于终结点的 auth_mode。 API 返回包含密钥和令牌的 JSON 输出。
提示
该 jq 实用工具用于演示如何从 JSON 输出中提取特定信息。 但是,可以将任何合适的工具用于该目的。
当终结点的 auth_mode 为 key
使用 listkeys API。
密钥在 primaryKey 和 secondaryKey 字段中返回。
response=$(curl -H "Content-Length: 0" --location --request POST \
"https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/$ENDPOINT_NAME/listkeys?api-version=$API_VERSION" \
--header "Authorization: Bearer $CONTROL_PLANE_TOKEN")
export DATA_PLANE_TOKEN=$(echo $response | jq -r '.primaryKey')
当终结点的 auth_mode 为 aml_token
使用 token API。
令牌在 accessToken 字段中返回。
令牌过期时间在 expiryTimeUtc 字段中返回。
令牌刷新时间在 refreshAfterTimeUtc 字段中返回。
response=$(curl -H "Content-Length: 0" --location --request POST \
"https://management.chinacloudapi.cn/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.MachineLearningServices/workspaces/$WORKSPACE/onlineEndpoints/$ENDPOINT_NAME/token?api-version=$API_VERSION" \
--header "Authorization: Bearer $CONTROL_PLANE_TOKEN")
export DATA_PLANE_TOKEN=$(echo $response | jq -r '.accessToken')
export EXPIRY_TIME_UTC=$(echo $response | jq -r '.expiryTimeUtc')
export REFRESH_AFTER_TIME_UTC=$(echo $response | jq -r '.refreshAfterTimeUtc')
当终结点的 auth_mode 为 aad_token
- 可以根据请求令牌的来源选择使用 IMDS 终结点或 MSI 终结点。
- 令牌在
accessToken 字段中返回。
- 令牌过期时间在
expiryTimeUtc 字段中返回。
通过 Azure 虚拟机
可以根据 Azure VM 的托管标识(当 VM 启用托管标识时)获取令牌。
若要获取针对具有托管标识的 Azure VM 的数据平面操作的 Microsoft Entra 令牌(aad_token),请将请求提交到 Azure 资源终结点的 IMDS 终结点 studio.ml.azure.cn:
export DATA_PLANE_TOKEN=$(curl -s \
'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fstudio.ml.azure.cn%2F' \
-H Metadata:true | jq -r '.access_token')
export EXPIRY_TIME_UTC=$(curl -s \
'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fstudio.ml.azure.cn%2F' \
-H Metadata:true | jq -r '.expiryTimeUtc')
若要详细了解如何基于托管标识获取令牌,请参阅使用 HTTP 获取令牌。
从计算实例
如果使用 Azure 机器学习工作区的计算实例,则可以获取令牌。 要获取令牌,你必须将计算实例托管标识的客户端 ID 和机密传递到在计算实例本地配置的 MSI 终结点。 可以从环境变量 MSI_ENDPOINT、DEFAULT_IDENTITY_CLIENT_ID 和 MSI_SECRET 分别获取 MSI 终结点、客户端 ID 和机密。 如果为计算实例启用托管标识,会自动设置这些变量。
从工作区的计算实例获取 Azure 资源终结点 studio.ml.azure.cn 的令牌:
export DATA_PLANE_TOKEN=$(curl -s \
"${MSI_ENDPOINT}?api-version=2018-02-01&resource=https%3A%2F%2Fstudio.ml.azure.cn%2F&clientid=${DEFAULT_IDENTITY_CLIENT_ID}" \
-H Metadata:true \
-H "Secret:$MSI_SECRET" | jq -r '.access_token')
export EXPIRY_TIME_UTC=$(curl -s \
"${MSI_ENDPOINT}?api-version=2018-02-01&resource=https%3A%2F%2Fstudio.ml.azure.cn%2F&clientid=${DEFAULT_IDENTITY_CLIENT_ID}" \
-H Metadata:true \
-H "Secret:$MSI_SECRET" | jq -r '.expiryTimeUtc')
重要
数据平面操作的 Microsoft Entra 令牌是从 Azure 资源终结点 management.chinacloudapi.cn 检索的,这与从 studio.ml.azure.cn 检索的控制平面操作的 Microsoft Entra 令牌不同。
可以在部署页的“ 使用 ”选项卡上找到密钥、Azure 机器学习令牌或Microsoft Entra 令牌。
验证 Microsoft Entra 令牌的资源终结点和客户端 ID
获取 Entra 令牌后,可以通过 studio.ml.azure.cn 解码令牌来验证令牌是否适用于正确的 Azure 资源终结点,以及正确的客户端 ID,这将返回包含以下信息的 JSON 响应:
{
"aud": "https://studio.ml.azure.cn",
"oid": "<your-object-id>"
}
使用密钥或令牌对数据评分
可以将 az ml online-endpoint invoke 用于具有密钥或 Azure 机器学习令牌或 Microsoft Entra 令牌的终结点。 CLI 自动提供密钥或令牌,因此无需显式传递密钥或令牌。
az ml online-endpoint invoke -n my-endpoint -r request.json
参考: az ml online-endpoint invoke
Azure 机器学习 SDK ml_client.online_endpoints.invoke() 支持密钥、Azure 机器学习令牌和 Microsoft Entra 令牌。
还可以使用通用 Python SDK 将 POST 请求发送到评分 URI。
调用联机终结点进行评分时,请在授权标头中传递密钥或令牌。 以下代码演示如何通过通用 Python SDK 使用密钥或令牌来调用联机终结点。 在代码中,将 api_key 变量替换为你的密钥或令牌。
import urllib.request
import json
import os
data = {"data": [
[1,2,3,4,5,6,7,8,9,10],
[10,9,8,7,6,5,4,3,2,1]
]}
body = str.encode(json.dumps(data))
url = '<scoring URI as retrieved earlier>'
api_key = '<key or token as retrieved earlier>'
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
print(result)
except urllib.error.HTTPError as error:
print("The request failed with status code: " + str(error.code))
# Print the headers - useful for debugging
print(error.info())
print(error.read().decode("utf8", 'ignore'))
或者,使用 SDK invoke() 的方法:
ml_client.online_endpoints.invoke(
endpoint_name="my-endpoint",
request_file="./sample-request.json"
)
参考: OnlineEndpointOperations.invoke
调用联机终结点进行评分时,请在授权标头中传递密钥、Azure 机器学习令牌或 Microsoft Entra 令牌。 以下代码演示如何使用 cURL 实用工具通过密钥或令牌调用联机终结点:
curl --request POST "$scoringUri" \
--header "Authorization: Bearer $DATA_PLANE_TOKEN" \
--header 'Content-Type: application/json' \
--data @endpoints/online/model-1/sample-request.json
密钥或 Azure 机器学习令牌
部署详细信息页的“ 测试 ”选项卡支持使用密钥、Azure 机器学习令牌或Microsoft Entra 令牌身份验证的终结点评分。
日志和监视器流量
若要在终结点的诊断设置中启用流量日志记录,请完成 “启用日志”中的步骤。
如果启用了诊断设置,可以查看 AmlOnlineEndpointTrafficLogs 表以查看身份验证模式和用户标识。
相关内容