Skip to main content

Managed Identity — local development

Managed Identity (local development) 🔒

This short guide describes recommended ways to develop and test the tenant-focused, Managed Identity-first authentication patterns used across the project.

High-level guidance

  • The tenant should prefer Managed Identity in all environments; keys are only a fallback for local debugging or short-lived CI runs.
  • For local development, the easiest approaches are: 1) interactive az login (DefaultAzureCredential picks this up) or 2) use a service principal (client-id/secret) for deterministic CI-style testing.

  1. Sign in interactively:
az login
# if multi-subscription: az account set --subscription <SUBSCRIPTION_ID>
  1. Keep AZURE_FOUNDRY_USE_MANAGED_IDENTITY=true (or other *_USE_MANAGED_IDENTITY flags) in the local .env when testing Managed Identity-based flows.

  2. Verify access to a resource via an access token (optional):

az account get-access-token --resource https://cognitiveservices.azure.com/

DefaultAzureCredential (used by the providers in this repo) will use the interactive login session automatically when present.


Option B — Service principal (use for reproducible CI/dev tests)

  1. Create a service principal (grant only the minimal needed role):
az ad sp create-for-rbac --name "mastra-dev-sp" --role "Contributor" --scopes /subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RG>
  1. Export the resulting credentials into the environment (do not commit these to source control):
export AZURE_CLIENT_ID="<appId>"
export AZURE_TENANT_ID="<tenant>"
export AZURE_CLIENT_SECRET="<password>"
# Set provider preferences to use service principal credentials (DefaultAzureCredential will pick these up)
export AZURE_FOUNDRY_USE_MANAGED_IDENTITY=true
  1. Run the local server or test scripts; the SDK will prefer the service principal credentials when they are present.

Notes & tips

  • Avoid committing client secrets; use a secrets store or CI secrets for tests that require a secret.
  • When a user-assigned managed identity must be tested, prefer running in a short-lived environment (dev subscription) where the identity can be assigned and tested there rather than attempting to emulate it locally.
  • If testing a fallback key is required, populate AZURE_INFERENCE_API_KEY (or legacy AZURE_OPENAI_SUBSCRIPTION_KEY) or AZURE_CONTENT_SAFETY_KEY only in secure local secrets and remove them when done.

If a short example for a chosen provider (OpenAI or Content Safety) would be helpful, indicate which provider to target and an example snippet will be added.