Authentication overview
Microsoft Cognitive Services, a collection of cloud-based AI services, requires authentication to ensure secure access to its APIs. This authentication process verifies the identity of the client (application or user) attempting to interact with the service, controlling who can access specific AI capabilities like vision, speech, language, and decision-making. Proper authentication is critical for protecting data, preventing unauthorized usage, and managing resource consumption within your Azure subscription.
The choice of authentication method depends on the application's requirements, security posture, and integration complexity. For instance, simpler applications or development environments might favor API keys for their ease of implementation, while enterprise-grade solutions often necessitate the advanced security features and centralized identity management offered by Azure Active Directory (Azure AD) and OAuth 2.0. All communication with Azure AI services is encrypted using Transport Layer Security (TLS) 1.2 or higher, ensuring data confidentiality and integrity during transit Azure AI services security in transit.
Supported authentication methods
Microsoft Cognitive Services supports two primary authentication methods:
- API Keys (Subscription Keys): These are secret keys generated when you create a Cognitive Services resource in Azure. They grant direct access to the services associated with that resource. API keys are suitable for development, testing, and applications with simpler security requirements.
- Azure Active Directory (Azure AD) with OAuth 2.0: This method leverages Azure AD for identity management and OAuth 2.0 for authorization. It provides more robust security features, including centralized identity control, role-based access control (RBAC), and token-based authentication. Azure AD is recommended for production environments and applications requiring fine-grained access management.
Here's a comparison of the supported methods:
| Method | When to Use | Security Level |
|---|---|---|
| API Keys (Subscription Keys) | Development, testing, simple applications. Quick setup and direct access. | Moderate. Requires careful key management to prevent exposure. One key grants broad access to the resource. |
| Azure Active Directory (Azure AD) + OAuth 2.0 | Production environments, enterprise applications, scenarios requiring granular access control, user identity integration. | High. Token-based, time-limited access, integrates with Azure RBAC, centralized identity management. OAuth 2.0 specification details. |
Getting your credentials
The process for obtaining credentials varies depending on the chosen authentication method.
For API Keys:
- Create a Cognitive Services Resource: Navigate to the Azure portal, search for "Cognitive Services," and create a new resource (e.g., "Multi-service Account" or a specific service like "Language Service").
- Locate Keys and Endpoint: Once the resource is deployed, go to its "Keys and Endpoint" blade in the Azure portal. You will find two API keys (Key 1 and Key 2) and the service endpoint URL. Use either key; Key 2 is provided for key rotation purposes.
- Copy Credentials: Copy one of the keys and the endpoint URL. These will be used in your API requests.
For Azure Active Directory (Azure AD) and OAuth 2.0:
Implementing Azure AD authentication involves several steps to configure an application registration and retrieve access tokens:
- Register an Application in Azure AD:
- In the Azure portal, navigate to "Azure Active Directory," then "App registrations."
- Click "New registration," provide a name for your application, and select supported account types.
- Configure a redirect URI if your application is a public client (e.g., web app, mobile app) Azure AD application registration quickstart.
- Grant API Permissions:
- In your registered application, go to "API permissions."
- Add a permission for "Azure AI Services" (or the specific Cognitive Service you are using). Grant delegated or application permissions as required by your application's architecture (e.g.,
user_impersonationfor delegated permissions).
- Create a Client Secret (for confidential clients):
- If your application is a confidential client (e.g., web app, daemon service), go to "Certificates & secrets" and create a new client secret. Note its value immediately, as it cannot be retrieved later.
- Obtain an Access Token:
- Your application will need to acquire an OAuth 2.0 access token from Azure AD. This typically involves an HTTP POST request to the Azure AD token endpoint, exchanging client credentials (client ID, client secret) or an authorization code for an access token.
- The access token is a JSON Web Token (JWT) that proves your application's identity and its authorized permissions. It has a limited lifespan and must be refreshed periodically.
- Use the Token: Include the obtained access token in the
Authorizationheader of your API requests to Microsoft Cognitive Services, prefixed withBearer.
Authenticated request example
Here's an example of an authenticated request using Python, demonstrating both API key and Azure AD authentication for a hypothetical Cognitive Services text analysis endpoint.
Using an API Key (Subscription Key):
This example sends a request to a text analysis service. Replace YOUR_ENDPOINT and YOUR_API_KEY with your actual service endpoint and subscription key.
import requests
import json
endpoint = "YOUR_ENDPOINT/text/analytics/v3.1/sentiment"
api_key = "YOUR_API_KEY"
headers = {
'Ocp-Apim-Subscription-Key': api_key,
'Content-Type': 'application/json',
}
data = {
"documents": [
{"id": "1", "language": "en", "text": "The food was excellent and the staff were very friendly."},
{"id": "2", "language": "en", "text": "The hotel was terrible. I would not recommend it."}
]
}
try:
response = requests.post(endpoint, headers=headers, json=data)
response.raise_for_status() # Raise an exception for HTTP errors
print(json.dumps(response.json(), indent=2))
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
Using Azure AD Access Token:
This example assumes you have already obtained an Azure AD access token. The process of getting the token itself varies based on your application type (e.g., client credentials flow for daemon apps, authorization code flow for web apps). For simplicity, we'll show how to use a pre-existing token.
Replace YOUR_ENDPOINT and YOUR_ACCESS_TOKEN with your actual service endpoint and the dynamically acquired access token.
import requests
import json
endpoint = "YOUR_ENDPOINT/text/analytics/v3.1/sentiment"
access_token = "YOUR_ACCESS_TOKEN" # This token must be acquired from Azure AD
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json',
}
data = {
"documents": [
{"id": "1", "language": "en", "text": "This is a great service!"},
{"id": "2", "language": "en", "text": "I had a really bad experience."}
]
}
try:
response = requests.post(endpoint, headers=headers, json=data)
response.raise_for_status() # Raise an exception for HTTP errors
print(json.dumps(response.json(), indent=2))
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
Security best practices
Properly securing your Microsoft Cognitive Services resources is paramount. Adhere to these best practices:
- Never hardcode credentials: Avoid embedding API keys or client secrets directly into your code. Use environment variables, Azure Key Vault, or other secure configuration management systems. Azure Key Vault is a recommended service for securely storing and managing secrets Azure Key Vault best practices.
- Rotate API Keys regularly: Periodically change your API keys to minimize the risk of compromise. Azure provides two keys (Key 1 and Key 2) to facilitate rotation without service interruption.
- Implement Least Privilege: When using Azure AD, grant only the minimum necessary permissions to your application or user identities. Use Azure Role-Based Access Control (RBAC) to define granular access policies.
- Monitor usage and access logs: Regularly review Azure Monitor logs and Azure AD sign-in logs to detect unusual activity or potential security breaches.
- Restrict network access: Configure network security features like Azure Virtual Networks (VNets), Private Endpoints, and IP firewalls to limit access to your Cognitive Services resources to authorized networks only.
- Secure client secrets: If using client secrets for Azure AD authentication, treat them with the same care as passwords. Store them securely and rotate them according to your organization's security policies.
- Use Managed Identities: For applications hosted on Azure (e.g., Azure App Service, Azure Functions, Azure VMs), use Managed Identities for Azure resources. This eliminates the need for developers to manage credentials directly, as Azure automatically handles the lifecycle of the identity and its authentication to Azure AD.
- Validate and sanitize inputs: Although primarily for application security, ensuring that inputs to Cognitive Services APIs are validated and sanitized can prevent certain types of attacks, such as injection vulnerabilities, if the input is derived from untrusted sources.
- Stay updated: Keep your SDKs, libraries, and Azure CLI tools updated to benefit from the latest security patches and features.