Skip to main content

Challenge 04: SDKs, REST APIs, and Authentication

Estimated Time

45 min | Cost: ~$0.25 | Domain: Plan & Manage AI Solutions (20-25%)

Exam skills covered

  • Install SDKs and APIs for Azure AI services
  • Determine the default endpoint for a service
  • Manage authentication using keys and Microsoft Entra ID
  • Implement DefaultAzureCredential for production workloads
  • Understand API versioning and SDK compatibility

Overview

Azure AI services can be consumed via language-specific SDKs or direct REST API calls. The AI-102 exam tests your ability to choose the right authentication method, understand endpoint construction, and handle API versioning correctly.

There are two primary authentication patterns: key-based (using AzureKeyCredential or the Ocp-Apim-Subscription-Key header) and Microsoft Entra ID (using DefaultAzureCredential with OAuth2 bearer tokens). Key-based auth is simpler but less secure—keys can be leaked and don't provide identity-based audit trails. Entra ID auth requires a custom subdomain and proper RBAC role assignments but provides managed identity support, conditional access, and fine-grained auditing.

This challenge walks you through both authentication methods using the Azure AI Text Analytics SDK, demonstrates REST API calls with proper headers, and shows how DefaultAzureCredential cascades through multiple credential types for seamless local-to-cloud development.

Architecture

You'll authenticate to Azure AI Language using both key-based and Entra ID methods, make the same API call with each, and compare the request patterns.

Challenge 04 topology

Prerequisites

  • Azure subscription with an Azure AI Language resource (with custom subdomain)
  • Azure CLI 2.50+ installed and logged in
  • Python 3.9+ with pip or .NET 8 SDK
  • Role assignment: "Cognitive Services User" on the resource for Entra ID auth

Implementation

Task 1: Key-Based Authentication with Azure AI Text Analytics

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

# Key-based authentication
endpoint = os.environ["AZURE_AI_ENDPOINT"] # https://<name>.cognitiveservices.azure.com/
key = os.environ["AZURE_AI_KEY"]

credential = AzureKeyCredential(key)
client = TextAnalyticsClient(endpoint=endpoint, credential=credential)

# Detect language
documents = [
"This is a document written in English.",
"Este es un documento escrito en español.",
"Dies ist ein auf Deutsch verfasstes Dokument."
]

result = client.detect_language(documents=documents)

for doc in result:
if not doc.is_error:
print(f"'{doc.primary_language.name}' (confidence: {doc.primary_language.confidence_score:.2f})")
else:
print(f"Error: {doc.error.code} - {doc.error.message}")

Task 2: Microsoft Entra ID Authentication with DefaultAzureCredential

import os
from azure.identity import DefaultAzureCredential
from azure.ai.textanalytics import TextAnalyticsClient

# Entra ID authentication (requires custom subdomain on resource)
endpoint = os.environ["AZURE_AI_ENDPOINT"] # Must be custom: https://<name>.cognitiveservices.azure.com/

# DefaultAzureCredential tries: Environment → Managed Identity → Azure CLI → etc.
credential = DefaultAzureCredential()
client = TextAnalyticsClient(endpoint=endpoint, credential=credential)

# Same API call, different auth method
documents = ["Azure AI services support multiple authentication methods."]

# Sentiment analysis
result = client.analyze_sentiment(documents=documents)

for doc in result:
if not doc.is_error:
print(f"Sentiment: {doc.sentiment}")
print(f" Positive: {doc.confidence_scores.positive:.2f}")
print(f" Neutral: {doc.confidence_scores.neutral:.2f}")
print(f" Negative: {doc.confidence_scores.negative:.2f}")

# Key phrase extraction
keyphrases = client.extract_key_phrases(documents=documents)
for doc in keyphrases:
if not doc.is_error:
print(f"Key phrases: {', '.join(doc.key_phrases)}")

Task 3: Assign RBAC Role and Understand Credential Chain

from azure.identity import DefaultAzureCredential, ChainedTokenCredential
from azure.identity import AzureCliCredential, ManagedIdentityCredential

# DefaultAzureCredential tries credentials in this order:
# 1. EnvironmentCredential (AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET)
# 2. WorkloadIdentityCredential (Kubernetes)
# 3. ManagedIdentityCredential (Azure VMs, App Service, Functions)
# 4. AzureCliCredential (local dev with 'az login')
# 5. AzurePowerShellCredential
# 6. AzureDeveloperCliCredential

# For production: use managed identity explicitly
production_credential = ManagedIdentityCredential()

# For local development: use Azure CLI
dev_credential = AzureCliCredential()

# Custom chain for specific needs
custom_credential = ChainedTokenCredential(
ManagedIdentityCredential(),
AzureCliCredential()
)

# Verify which credential is being used
from azure.identity import DefaultAzureCredential
import logging

logging.basicConfig(level=logging.DEBUG)
logging.getLogger("azure.identity").setLevel(logging.DEBUG)

credential = DefaultAzureCredential()
# Logs will show which credential in the chain succeeded

# Required RBAC role: "Cognitive Services User"
# az role assignment create \
# --assignee <principal-id> \
# --role "Cognitive Services User" \
# --scope /subscriptions/<sub>/resourceGroups/<rg>/providers/Microsoft.CognitiveServices/accounts/<name>

Expected Output

'English' (confidence: 1.00)
'Spanish' (confidence: 1.00)
'German' (confidence: 1.00)

Sentiment: neutral
Positive: 0.10
Neutral: 0.88
Negative: 0.02
Key phrases: Azure AI services, multiple authentication methods

Auth successful! Detected: English

Break & fix

ScenarioSymptomRoot CauseFix
Entra auth 401AuthenticationFailedMissing RBAC role assignmentAssign "Cognitive Services User" role to the identity
Custom domain missingInvalidAuthentication with bearer tokenResource uses regional endpoint (no custom subdomain)Recreate resource with --custom-domain parameter
Wrong token audience401 UnauthorizedToken requested for wrong resourceUse https://cognitiveservices.azure.com as the resource/scope
SDK version mismatchApiVersionNotSupportedSDK version expects newer API versionPin API version or upgrade SDK package
Key in wrong header401 with REST callUsing api-key instead of Ocp-Apim-Subscription-KeyAzure AI services use Ocp-Apim-Subscription-Key; Azure OpenAI uses api-key

Knowledge Check

1. Which RBAC role is the minimum required for an application to make inference calls to Azure AI services using Microsoft Entra authentication?

2. Your application runs on Azure App Service and needs to authenticate to Azure AI Language without storing credentials. What should you use?

3. What is the correct HTTP header name for API key authentication when calling Azure AI services (non-OpenAI) via REST?

4. DefaultAzureCredential fails locally with 'No credential in this chain provided a token'. What is the most likely fix?

5. You need to call Azure AI Language with API version '2023-04-01' but the latest SDK defaults to '2024-04-01'. How should you handle this?

Cleanup

az group delete --name rg-ai102-challenge04 --yes --no-wait

Learn More