Authenticate requests to Azure Cognitive Services

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

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. 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.

You can get your subscription key from the Azure portal after creating your account, or activating a free trial.

Authentication headers

Let's quickly review the authentication headers available for use with Azure Cognitive Services.

Header Description
Ocp-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-Region 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.
Authorization Use this header if you are using an authentication token. The steps to perform a token exchange are detailed in the following sections. 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. The keys are available in the Azure portal for each resource that you've created. To use a subscription key to authenticate a request, it must be passed along as the Ocp-Apim-Subscription-Key header.

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.

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

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

Warning

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.

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

When using the multi-service subscription key to make a request to api.cognitive.microsoft.com, you must include the region in the URL. For example: westus.api.cognitive.microsoft.com.

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

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

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

Some Azure Cognitive Services accept, and in some cases require, an authentication token. Currently, these services support authentication tokens:

  • Text Translation API
  • Speech Services: Speech-to-text REST API
  • Speech Services: Text-to-speech REST API

Note

QnA Maker also uses the Authorization header, but requires an endpoint key. For more information, see QnA Maker: Get answer from knowledge base.

Warning

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. Authentication tokens are valid for 10 minutes.

Authentication tokens are included in a request as the Authorization header. The token value provided must be preceded by Bearer, for example: Bearer YOUR_AUTH_TOKEN.

Sample requests

Use 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

After you get an authentication token, you'll need to pass it in each request as the Authorization header. 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

Authenticate with Azure Active Directory

Important

Currently, only the Computer Vision API, Face API, Text Analytics API, and Immersive Reader support authentication using Azure Active Directory (AAD).

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. Let's take a look at what's required to authenticate using Azure Active Directory (AAD).

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. 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. 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.

Note

Keep in mind that AAD role assignments may take up to five minutes to propagate.

  1. 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
    

    You're going to need the ApplicationId in the next step.

  2. Next, you need to create a service principal for the AAD application.

    New-AzADServicePrincipal -ApplicationId <APPLICATION_ID>
    

    Note

    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

    The ObjectId of the service principal is used, not the ObjectId for the application. The ACCOUNT_ID will be the Azure resource Id of the Cognitive Services account you created. 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. The token provided is then used to call the Computer Vision API.

  1. Get 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. 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. 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