Authentication overview

Authentication for Microsoft Azure Cognitive Services ensures that only authorized applications and users can access the AI capabilities provided. This process involves verifying the identity of the client requesting access to services like Vision, Speech, or Language. Azure Cognitive Services offers several methods for authentication, catering to different deployment scenarios and security requirements, from simple API key access to robust identity management with Azure Active Directory (Azure AD).

Choosing the appropriate authentication method depends on factors such as the application's hosting environment, its need to interact with other Azure resources, and the desired level of credential management. Proper authentication is a foundational element of secure application design, preventing unauthorized access and potential misuse of Cognitive Services resources.

Supported authentication methods

Azure Cognitive Services supports two primary authentication methods:

  1. Subscription Keys (API Keys): This is the simplest and most common method for quick setup and development. Each Cognitive Services resource created in Azure comes with two subscription keys. These keys are passed in the HTTP request header to authenticate access.
  2. Azure Active Directory (Azure AD): For enterprise-grade security and integration with existing identity management, Azure AD provides token-based authentication. This method allows for fine-grained access control using role-based access control (RBAC) and eliminates the need to manage secret keys directly within your application code. Azure AD authentication supports various flows, including service principals and managed identities.

The following table outlines these methods, their use cases, and security considerations:

Method When to Use Security Level
Subscription Keys Rapid prototyping, simple applications, scenarios where key rotation is manually managed. Moderate (requires secure key management and rotation)
Azure Active Directory (Service Principals) Production applications, multi-service environments, scenarios requiring granular RBAC, applications running outside Azure. High (leveraged by centralized identity management, supports token-based access)
Azure Active Directory (Managed Identities) Azure-hosted applications (VMs, App Services, Functions) needing to access other Azure resources securely without credential management. High (Azure manages identity lifecycle, no credentials in code)

Getting your credentials

The process for obtaining credentials varies based on the chosen authentication method:

Subscription Keys

  1. Create a Cognitive Services resource: Navigate to the Azure portal and create a new Cognitive Services resource (e.g., Speech, Language, Vision).
  2. Locate keys and endpoint: Once the resource is deployed, go to the resource's "Keys and Endpoint" section in the Azure portal. You will find two subscription keys (Key 1 and Key 2) and the service endpoint URL. Either key can be used for authentication.

Azure Active Directory (Service Principals)

  1. Register an application in Azure AD: In the Azure portal, navigate to Azure Active Directory > App registrations > New registration. Provide a name and configure access as needed.
  2. Create a client secret or upload a certificate: For the registered application, go to "Certificates & secrets" to generate a new client secret or upload a certificate. Note the secret value immediately as it cannot be retrieved later.
  3. Assign roles to the application: Grant the service principal appropriate roles (e.g., "Cognitive Services User") on your Cognitive Services resource or resource group. This is done under the resource's "Access control (IAM)" section.
  4. Obtain tenant ID and client ID: The application (client) ID and directory (tenant) ID can be found on the "Overview" page of your registered application.

Azure Active Directory (Managed Identities)

Managed identities are designed for Azure-hosted applications and eliminate the need to manage secrets directly. They are automatically managed by Azure.

  1. Enable managed identity: For your Azure resource (e.g., Azure VM, App Service, Azure Function), enable a system-assigned or user-assigned managed identity through its settings in the Azure portal.
  2. Assign roles to the managed identity: Grant the managed identity appropriate roles (e.g., "Cognitive Services User") on your Cognitive Services resource via the resource's "Access control (IAM)" section.

For detailed steps on configuring Azure AD for Cognitive Services, refer to the Azure AI Services authentication documentation.

Authenticated request example

This example demonstrates how to make an authenticated request to the Azure Cognitive Services Text Analytics API (specifically for sentiment analysis) using a subscription key in Python. Developers can choose from Python, JavaScript, Java, .NET, and Go SDKs to interact with the services.

Using a Subscription Key (Python)


import requests

# Replace with your actual endpoint and key
service_endpoint = "https://YOUR_REGION.api.cognitive.microsoft.com/text/analytics/v3.1/sentiment"
subscription_key = "YOUR_COGNITIVE_SERVICES_KEY"

headers = {
    "Ocp-Apim-Subscription-Key": subscription_key,
    "Content-Type": "application/json"
}

documents = {
    "documents": [
        {"id": "1", "language": "en", "text": "The food was delicious and the staff were friendly!"},
        {"id": "2", "language": "en", "text": "The service was slow, but the atmosphere was nice."}
    ]
}

try:
    response = requests.post(service_endpoint, headers=headers, json=documents)
    response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
    print(response.json())
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Using Azure AD (Python with Azure Identity library)

For Azure AD, the azure-identity library simplifies token acquisition. This example uses DefaultAzureCredential, which attempts to authenticate using several common mechanisms (environment variables, managed identity, Azure CLI, etc.).


from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
from azure.identity import DefaultAzureCredential

# Replace with your actual endpoint
service_endpoint = "https://YOUR_REGION.api.cognitive.microsoft.com"

# When using Azure AD, you don't provide a key directly
# DefaultAzureCredential will attempt to authenticate via environment variables, managed identity, Azure CLI, etc.
credential = DefaultAzureCredential()

text_analytics_client = TextAnalyticsClient(endpoint=service_endpoint, credential=credential)

documents = [
    "The food was delicious and the staff were friendly!",
    "The service was slow, but the atmosphere was nice."
]

result = text_analytics_client.analyze_sentiment(documents=documents)

for doc in result:
    print(f"Document ID: {doc.id}, Sentiment: {doc.sentiment}")

This Python snippet demonstrates how to authenticate using DefaultAzureCredential. For applications hosted in Azure, DefaultAzureCredential can automatically leverage Azure managed identities, removing the need for explicit credential management in code.

Security best practices

Implementing robust security practices is critical when working with Azure Cognitive Services:

  • Securely store API keys: Never hardcode subscription keys directly into your application code. Use environment variables, configuration files, or, ideally, a dedicated secret management service like Azure Key Vault. Azure Key Vault provides a secure store for credentials, certificates, and other secrets, with fine-grained access policies to control who can access them.
  • Regularly rotate API keys: Azure Cognitive Services provides two keys (Key 1 and Key 2) to facilitate rotation without service interruption. Use one key while rotating the other, then update your application and switch. This practice mitigates the risk if a key is compromised.
  • Use Azure AD with RBAC: Whenever possible, prefer Azure Active Directory authentication, especially for production environments. Azure AD allows you to define specific roles and assign them to users or service principals, adhering to the principle of least privilege. This ensures that an identity only has the permissions necessary to perform its intended functions.
  • Implement Managed Identities for Azure-hosted apps: For applications running within Azure (e.g., Azure App Service, Azure Functions, Azure VMs), use managed identities. This eliminates the need to manage credentials in your code or configuration files, as Azure automatically handles the identity lifecycle and authentication to other Azure services.
  • Restrict network access: Configure network security for your Cognitive Services resources. Use Azure Virtual Networks (VNets) and Private Endpoints to restrict access to your Cognitive Services endpoint from specific networks, preventing public internet exposure.
  • Monitor access and usage: Utilize Azure Monitor and Azure Activity Logs to track who is accessing your Cognitive Services resources and how they are being used. This helps detect unusual activity and potential security incidents.
  • Encrypt data in transit and at rest: Azure Cognitive Services encrypts data at rest and in transit. Ensure your client applications also adhere to secure communication protocols (e.g., HTTPS) to protect data before it reaches Azure. This is part of a broader security strategy for cloud services, as detailed by organizations like the Cloud Security Alliance.