驗證 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 free 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 只有在搭配翻譯工具文字 API 使用多服務訂用帳戶金鑰時才需要此標頭。This header is only required when using a multi-service subscription key with the Translator Text API. 使用此標頭指定訂用帳戶區域。Use this header to specify the subscription region.
AuthorizationAuthorization 如果您使用驗證權杖,請使用此標頭。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

第一個選項是使用特定服務 (例如翻譯工具文字) 的訂用帳戶金鑰來驗證要求。The first option is to authenticate a request with a subscription key for a specific service, like Translator Text. 金鑰適用於 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.

這是 Bing Web 搜尋 API 的範例呼叫:This is a sample call to the Bing Web Search API:

curl -X GET 'https://api.cognitive.microsoft.com/bing/v7.0/search?q=Welsch%20Pembroke%20Corgis' \
-H 'Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY' | json_pp

這是翻譯工具文字 API 的範例呼叫:This is a sample call to the Translator Text API:

curl -X POST 'https://api.cognitive.microsofttranslator.com/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

以下影片將示範如何使用認知服務金鑰。The following video demonstrates using a Cognitive Services key.

使用多服務訂用帳戶金鑰進行驗證Authenticate with a multi-service subscription key

警告

目前,以下服務支援多服務金鑰: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.

認知服務的多服務訂用帳戶金鑰示範Multi-service subscription key demonstration for Cognitive Services

支援區域Supported regions

當使用多服務訂用帳戶金鑰對 api.cognitive.microsoft.com 提出要求時,您必須在 URL 中包含區域。When using the multi-service subscription key to make a request to api.cognitive.microsoft.com, you must include the region in the URL. 例如: westus.api.cognitive.microsoft.comFor example: westus.api.cognitive.microsoft.com.

當搭配翻譯工具文字 API 使用多服務訂用帳戶金鑰時,您必須指定訂用帳戶區域與 Ocp-Apim-Subscription-Region 標頭。When using multi-service subscription key with the Translator Text API, you must specify the subscription region with the Ocp-Apim-Subscription-Region header.

在以下區域中支援多服務驗證:Multi-service authentication is supported in these regions:

australiaeast brazilsouth canadacentral
centralindia eastasia eastus
japaneast northeurope southcentralus
southeastasia uksouth westcentralus
westeurope westus westus2

範例要求Sample requests

這是 Bing Web 搜尋 API 的範例呼叫:This is a sample call to the Bing Web Search API:

curl -X GET 'https://YOUR-REGION.api.cognitive.microsoft.com/bing/v7.0/search?q=Welsch%20Pembroke%20Corgis' \
-H 'Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY' | json_pp

這是翻譯工具文字 API 的範例呼叫:This is a sample call to the Translator Text API:

curl -X POST 'https://api.cognitive.microsofttranslator.com/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

注意

QnA Maker 也會使用授權標頭,但需要端點金鑰。QnA Maker also uses the Authorization header, but requires an endpoint key. 如需詳細資訊,請參閱 QnA Maker:從知識庫中獲得答案For more information, see QnA Maker: Get answer from knowledge base.

警告

支援驗證權杖的服務可能會隨著時間變更,請在使用此驗證方法之前,檢查服務的 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.microsoft.com/sts/v1.0/issueTokenUse this URL to exchange a subscription key for an authentication token: https://YOUR-REGION.api.cognitive.microsoft.com/sts/v1.0/issueToken.

curl -v -X POST \
"https://YOUR-REGION.api.cognitive.microsoft.com/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:

australiaeast brazilsouth canadacentral
centralindia eastasia eastus
japaneast northeurope southcentralus
southeastasia uksouth westcentralus
westeurope westus westus2

取得驗證權杖之後,您必須在每個要求中加以傳遞作為 Authorization 標頭。After you get an authentication token, you'll need to pass it in each request as the Authorization header. 這是翻譯工具文字 API 的範例呼叫:This is a sample call to the Translator Text API:

curl -X POST 'https://api.cognitive.microsofttranslator.com/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

重要

目前,只有電腦視覺 API、臉部 api、文字分析 API 和沉浸式讀取器支援使用 AZURE ACTIVE DIRECTORY (AAD)進行驗證。Currently, only the Computer Vision API, Face API, Text Analytics API, and Immersive Reader support authentication using Azure Active Directory (AAD).

在前面幾節中,我們示範了如何使用單一服務或多服務訂用帳戶金鑰,針對 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 Cloud Shell 環境或 Azure CLI 來建立子域、指派角色,以及取得持有人權杖來呼叫 Azure 認知服務。In the following sections, you'll use either the Azure Cloud Shell environment or the Azure CLI to create a subdomain, assign roles, and obtain a bearer token to call the Azure Cognitive Services. 如果您停滯,會在每個區段中提供連結,其中包含 Azure Cloud Shell/Azure CLI 中每個命令的所有可用選項。If you get stuck, links are provided in each section with all available options for each command in Azure Cloud Shell/Azure CLI.

建立具有自訂子域的資源Create a resource with a custom subdomain

第一個步驟是建立自訂子域。The first step is to create a custom subdomain.

  1. 從開啟 Azure Cloud Shell 開始。Start by opening the Azure Cloud Shell. 然後選取訂用帳戶:then select a subscription:

    Select-AzureSubscription -SubscriptionName <YOUR_SUBCRIPTION>
    
  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: ".", "!", ",".

    New-AzCognitiveServicesAccount -ResourceGroupName <RESOURCE_GROUP_NAME> -name <ACCOUNT_NAME> -Type <ACCOUNT_TYPE> -SkuName <SUBSCRIPTION_TYPE> -Location <REGION> -CustomSubdomainName <UNIQUE_SUBDOMAIN>
    
  3. 如果成功,端點應該會顯示資源的唯一子功能變數名稱稱。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.

注意

請記住,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
    
    New-AzADApplication -DisplayName <APP_DISPLAY_NAME> -IdentifierUris <APP_URIS> -Password $SecureStringPassword
    

    在下一個步驟中,您將需要ApplicationIdYou'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>
    

    注意

    如果您在 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.

    注意

    使用服務主體的 ObjectId,而不是應用程式的 ObjectId。The ObjectId of the service principal is used, not the ObjectId for the application. ACCOUNT_ID 將會是您所建立認知服務帳戶的 Azure 資源識別碼。The ACCOUNT_ID will be the Azure resource Id of the Cognitive Services account you created. 您可以從 Azure 入口網站資源的 [屬性] 中找到 Azure 資源識別碼。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. 取得您的TenantIdGet your TenantId:

    $context=Get-AzContext
    $context.Tenant.Id
    
  2. 取得權杖:Get a token:

    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList "https://login.windows.net/<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.com/", $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.

另請參閱See also