对 Azure 认知服务的请求进行身份验证Authenticate requests to Azure Cognitive Services

对 Azure 认知服务的每个请求都必须包含身份验证标头。Each request to an Azure Cognitive Service must include an authentication header. 此标头传递订阅密钥或访问令牌,用于验证服务或服务组订阅。This header passes along a subscription key or access token, which is used to validate your subscription for a service or group of services. 本文介绍三种对请求进行身份验证的方法以及每种方法的要求。In this article, you'll learn about three ways to authenticate a request and the requirements for each.

先决条件Prerequisites

在发出请求之前,需要具有 Azure 帐户和 Azure 认知服务订阅。Before you make a request, you need an Azure account and an Azure Cognitive Services subscription. 如果已有帐户,请继续并跳到下一节。If you already have an account, go ahead and skip to the next section. 如果还没有帐户,我们会提供指南,可在几分钟内完成设置:创建 Azure 认知服务帐户If you don't have an account, we have a guide to get you set up in minutes: Create a Cognitive Services account for Azure.

创建帐户后,可以从 Azure 门户获取订阅密钥或激活免费试用You can get your subscription key from the Azure portal after creating your account, or activating a trial trial.

身份验证标头Authentication headers

让我们快速查看可用于 Azure 认知服务的身份验证标头。Let's quickly review the authentication headers available for use with Azure Cognitive Services.

标头Header 说明Description
Ocp-Apim-Subscription-KeyOcp-Apim-Subscription-Key 使用此标头通过特定服务订阅密钥或多服务订阅密钥进行身份验证。Use this header to authenticate with a subscription key for a specific service or a multi-service subscription key.
Ocp-Apim-Subscription-RegionOcp-Apim-Subscription-Region 只有在使用具有 Translator 服务的多服务订阅密钥时才需要此标头。This header is only required when using a multi-service subscription key with the Translator service. 使用此标头指定订阅区域。Use this header to specify the subscription region.
授权Authorization 如果使用的是身份验证令牌,则使用此标头。Use this header if you are using an authentication token. 以下各节详细介绍了执行令牌交换的步骤。The steps to perform a token exchange are detailed in the following sections. 提供的值遵循以下格式:Bearer <TOKEN>The value provided follows this format: Bearer <TOKEN>.

使用单服务订阅密钥进行身份验证Authenticate with a single-service subscription key

第一个选项是使用特定服务(如 Translator)的订阅密钥对请求进行身份验证。The first option is to authenticate a request with a subscription key for a specific service, like Translator. Azure 门户中的密钥可用于已创建的每个资源。The keys are available in the Azure portal for each resource that you've created. 要使用订阅密钥对请求进行身份验证,必须将其作为 Ocp-Apim-Subscription-Key 标头传递。To use a subscription key to authenticate a request, it must be passed along as the Ocp-Apim-Subscription-Key header.

这些示例请求演示了如何使用 Ocp-Apim-Subscription-Key 标头。These sample requests demonstrates how to use the Ocp-Apim-Subscription-Key header. 请记住,使用此示例时,需要包括有效的订阅密钥。Keep in mind, when using this sample you'll need to include a valid subscription key.

这是对 Translator 服务的示例调用:This is a sample call to the Translator service:

curl -X POST 'https://api.translator.azure.cn/translate?api-version=3.0&from=en&to=de' \
-H 'Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY' \
-H 'Content-Type: application/json' \
--data-raw '[{ "text": "How much for the cup of coffee?" }]' | json_pp

使用多服务订阅密钥进行身份验证Authenticate with a multi-service subscription key

Warning

目前,以下服务**** 不支持多服务密钥:QnA Maker、语音服务、自定义视觉和异常检测器。At this time, these services don't support multi-service keys: QnA Maker, Speech Services, Custom Vision, and Anomaly Detector.

此选项仍使用订阅密钥对请求进行身份验证。This option also uses a subscription key to authenticate requests. 主要区别在于订阅密钥未绑定到特定服务,而单个密钥可用于对多个认知服务的请求进行身份验证。The main difference is that a subscription key is not tied to a specific service, rather, a single key can be used to authenticate requests for multiple Cognitive Services. 有关区域可用性、支持的功能和定价的信息,请参阅认知服务定价See Cognitive Services pricing for information about regional availability, supported features, and pricing.

订阅密钥在每个请求中作为 Ocp-Apim-Subscription-Key 标头提供。The subscription key is provided in each request as the Ocp-Apim-Subscription-Key header.

支持的区域Supported regions

使用多服务订阅密钥向 api.cognitive.azure.cn 发出请求时,必须在 URL 中包含该区域。When using the multi-service subscription key to make a request to api.cognitive.azure.cn, you must include the region in the URL. 例如:chinaeast2.api.cognitive.azure.cnFor example: chinaeast2.api.cognitive.azure.cn.

将多服务订阅密钥与 Translator 服务配合使用时,必须使用 Ocp-Apim-Subscription-Region 标头指定订阅区域。When using multi-service subscription key with the Translator service, you must specify the subscription region with the Ocp-Apim-Subscription-Region header.

以下区域支持多服务身份验证:Multi-service authentication is supported in these regions:

chinaeast2 chinanorth

示例请求Sample requests

这是对 Translator 服务的示例调用:This is a sample call to the Translator service:

curl -X POST 'https://api.translator.azure.cn/translate?api-version=3.0&from=en&to=de' \
-H 'Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY' \
-H 'Ocp-Apim-Subscription-Region: YOUR_SUBSCRIPTION_REGION' \
-H 'Content-Type: application/json' \
--data-raw '[{ "text": "How much for the cup of coffee?" }]' | json_pp

使用身份验证令牌进行身份验证Authenticate with an authentication token

某些 Azure 认知服务接受并在某些情况下需要身份验证令牌。Some Azure Cognitive Services accept, and in some cases require, an authentication token. 目前,以下服务支持身份验证令牌:Currently, these services support authentication tokens:

  • 文本翻译 APIText Translation API
  • 语音服务:语音转文本 REST APISpeech Services: Speech-to-text REST API
  • 语音服务:文本转语音 REST APISpeech Services: Text-to-speech REST API

Warning

支持身份验证令牌的服务可能会随时间而变化,请在使用此身份验证方法之前检查服务的 API 参考。The services that support authentication tokens may change over time, please check the API reference for a service before using this authentication method.

单服务订阅密钥和多服务订阅密钥均可用于交换认证令牌。Both single service and multi-service subscription keys can be exchanged for authentication tokens. 身份验证令牌有效期为 10 分钟。Authentication tokens are valid for 10 minutes.

身份验证令牌作为 Authorization 标头包含在请求中。Authentication tokens are included in a request as the Authorization header. 提供的令牌值必须以 Bearer 开头,例如:Bearer YOUR_AUTH_TOKENThe token value provided must be preceded by Bearer, for example: Bearer YOUR_AUTH_TOKEN.

示例请求Sample requests

使用此 URL 交换身份验证令牌的订阅密钥:https://YOUR-REGION.api.cognitive.azure.cn/sts/v1.0/issueTokenUse this URL to exchange a subscription key for an authentication token: https://YOUR-REGION.api.cognitive.azure.cn/sts/v1.0/issueToken.

curl -v -X POST \
"https://YOUR-REGION.api.cognitive.azure.cn/sts/v1.0/issueToken" \
-H "Content-type: application/x-www-form-urlencoded" \
-H "Content-length: 0" \
-H "Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY"

以下多服务区域支持令牌交换:These multi-service regions support token exchange:

chinaeast2 chinanorth

获得身份验证令牌后,需要在每个请求中将其作为 Authorization 标头传递。After you get an authentication token, you'll need to pass it in each request as the Authorization header. 这是对 Translator 服务的示例调用:This is a sample call to the Translator service:

curl -X POST 'https://api.translator.azure.cn/translate?api-version=3.0&from=en&to=de' \
-H 'Authorization: Bearer YOUR_AUTH_TOKEN' \
-H 'Content-Type: application/json' \
--data-raw '[{ "text": "How much for the cup of coffee?" }]' | json_pp

使用 Azure Active Directory 进行身份验证Authenticate with Azure Active Directory

Important

  1. 目前,仅计算机视觉 API、人脸 API、文本分析 API 支持使用 Azure Active Directory (AAD) 进行身份验证****。Currently, only the Computer Vision API, Face API, Text Analytics API support authentication using Azure Active Directory (AAD).
  2. AAD 身份验证必须始终与 Azure 资源的自定义子域名一起使用。AAD authentication needs to be always used together with custom subdomain name of your Azure resource. 区域终结点不支持 AAD 身份验证。Regional endpoints does not support AAD authentication.

在前面的部分中,我们演示了如何使用单一服务或多服务订阅密钥完成 Azure 认知服务的身份验证。In the previous sections, we showed you how to authenticate against Azure Cognitive Services using either a single-service or multi-service subscription key. 虽然这些密钥提供了一种快速简便的途径实现快速开始开发,但还不足以支持需要基于角色的访问控制的更复杂的方案。While these keys provide a quick and easy path to start development, they fall short in more complex scenarios that require role-based access controls. 让我们来看看使用 Azure Active Directory (AAD) 进行身份验证所需的条件。Let's take a look at what's required to authenticate using Azure Active Directory (AAD).

在以下部分中,你将使用 Azure CLI 创建子域、分配角色并获取持有者令牌来调用 Azure 认知服务。In the following sections, you'll use the Azure CLI to create a subdomain, assign roles, and obtain a bearer token to call the Azure Cognitive Services. 如果遇到问题,每个部分都提供了可供参考和使用的链接以及 Azure CLI 中每个命令的所有可用选项。If you get stuck, links are provided in each section with all available options for each command in Azure CLI.

使用自定义子域创建资源Create a resource with a custom subdomain

第一步是创建自定义子域。The first step is to create a custom subdomain. 如果要使用没有自定义子域名的现有认知服务资源,请按照认知服务自定义子域中的说明为资源启用自定义子域。If you want to use an existing Cognitive Services resource which does not have custom subdomain name, follow the instructions in Cognitive Services Custom Subdomains to enable custom subdomain for your resource.

  1. 首先打开 Azure CLI。Start by opening the Azure CLI. 然后选择一个订阅Then select a subscription:

    Set-AzContext -SubscriptionName <SubscriptionName>
    
  2. 接下来,使用自定义子域创建认知服务资源Next, create a Cognitive Services resource with a custom subdomain. 子域名需为全局唯一,不能包括特殊字符,例如:“.”、“!”、“,”。The subdomain name needs to be globally unique and cannot include special characters, such as: ".", "!", ",".

    $account = New-AzCognitiveServicesAccount -ResourceGroupName <RESOURCE_GROUP_NAME> -name <ACCOUNT_NAME> -Type <ACCOUNT_TYPE> -SkuName <SUBSCRIPTION_TYPE> -Location <REGION> -CustomSubdomainName <UNIQUE_SUBDOMAIN>
    
  3. 如果成功,Endpoint 应会显示资源独有的子域名****。If successful, the Endpoint should show the subdomain name unique to your resource.

向服务主体分配角色Assign a role to a service principal

现在,已有了与资源关联的自定义子域,接着需要将角色分配给服务主体。Now that you have a custom subdomain associated with your resource, you're going to need to assign a role to a service principal.

Note

请记住,AAD 角色分配可能需要最多五分钟的时间进行传播。Keep in mind that AAD role assignments may take up to five minutes to propagate.

  1. 首先,注册一个 AAD 应用程序First, let's register an AAD application.

    $SecureStringPassword = ConvertTo-SecureString -String <YOUR_PASSWORD> -AsPlainText -Force
    
    $app = New-AzADApplication -DisplayName <APP_DISPLAY_NAME> -IdentifierUris <APP_URIS> -Password $SecureStringPassword
    

    在下一步中,需要 ApplicationId****。You're going to need the ApplicationId in the next step.

  2. 接下来,需要为 AAD 应用程序创建服务主体Next, you need to create a service principal for the AAD application.

    New-AzADServicePrincipal -ApplicationId <APPLICATION_ID>
    

    Note

    如果在 Azure 门户中注册应用程序,将自动为你完成此步骤。If you register an application in the Azure portal, this step is completed for you.

  3. 最后一步是向服务主体分配“认知服务用户”角色(范围限定为资源)。The last step is to assign the "Cognitive Services User" role to the service principal (scoped to the resource). 通过分配角色,将向服务主体授予对此资源的访问权限。By assigning a role, you're granting service principal access to this resource. 可以向服务主体授予对订阅中多个资源的访问权限。You can grant the same service principal access to multiple resources in your subscription.

    Note

    此过程使用服务主体的 ObjectId,而不是应用程序的 ObjectId。The ObjectId of the service principal is used, not the ObjectId for the application. ACCOUNT_ID 是所创建的认知服务帐户的 Azure 资源 ID。The ACCOUNT_ID will be the Azure resource Id of the Cognitive Services account you created. 可以从 Azure 门户中资源的“属性”中找到 Azure 资源 ID。You can find Azure resource Id from "properties" of the resource in Azure portal.

    New-AzRoleAssignment -ObjectId <SERVICE_PRINCIPAL_OBJECTID> -Scope <ACCOUNT_ID> -RoleDefinitionName "Cognitive Services User"
    

示例请求Sample request

在此示例中,使用密码对服务主体进行身份验证。In this sample, a password is used to authenticate the service principal. 然后,使用提供的令牌调用计算机视觉 API。The token provided is then used to call the Computer Vision API.

  1. 获取 TenantId****:Get your TenantId:

    $context=Get-AzContext
    $context.Tenant.Id
    
  2. 获取令牌:Get a token:

    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList "https://login.partner.microsoftonline.cn/<TENANT_ID>"
    $secureSecretObject = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.SecureClientSecret" -ArgumentList $SecureStringPassword
    $clientCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $app.ApplicationId, $secureSecretObject
    $token=$authContext.AcquireTokenAsync("https://cognitiveservices.azure.cn/", $clientCredential).Result
    $token
    
  3. 调用计算机视觉 API:Call the Computer Vision API:

    $url = $account.Endpoint+"vision/v1.0/models"
    $result = Invoke-RestMethod -Uri $url  -Method Get -Headers @{"Authorization"=$token.CreateAuthorizationHeader()} -Verbose
    $result | ConvertTo-Json
    

或者,可以使用证书对服务主体进行身份验证。Alternatively, the service principal can be authenticated with a certificate. 除了服务主体之外,还通过使用另一个 AAD 应用程序来委派权限的方式提供用户主体支持。Besides service principal, user principal is also supported by having permissions delegated through another AAD application. 在这种情况下,获取令牌时,将提示用户进行双重身份验证,而不是提供密码或证书。In this case, instead of passwords or certificates, users would be prompted for two-factor authentication when acquiring token.

授权访问托管标识Authorize access to managed identities

认知服务支持使用 Azure 资源的托管标识进行 Azure Active Directory (Azure AD) 身份验证。Cognitive Services support Azure Active Directory (Azure AD) authentication with managed identities for Azure resources. Azure 资源的托管标识可以从 Azure 虚拟机 (VM)、函数应用、虚拟机规模集和其他服务中运行的应用程序使用 Azure AD 凭据授权对认知服务资源的访问权限。Managed identities for Azure resources can authorize access to Cognitive Services resources using Azure AD credentials from applications running in Azure virtual machines (VMs), function apps, virtual machine scale sets, and other services. 将 Azure 资源的托管标识与 Azure AD 身份验证结合使用,可避免将凭据随在云中运行的应用程序一起存储。By using managed identities for Azure resources together with Azure AD authentication, you can avoid storing credentials with your applications that run in the cloud.

在 VM 上启用托管标识Enable managed identities on a VM

在使用 Azure 资源的托管标识对 VM 中的认知服务资源授予访问权限之前,必须在 VM 上启用 Azure 资源的托管标识。Before you can use managed identities for Azure resources to authorize access to Cognitive Services resources from your VM, you must enable managed identities for Azure resources on the VM. 若要了解如何为 Azure 资源启用托管标识,请参阅:To learn how to enable managed identities for Azure Resources, see:

有关托管标识的详细信息,请参阅 Azure 资源的托管标识For more information about managed identities, see Managed identities for Azure resources.

另请参阅See also