Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Important
Secret-backed header values (secretRef) are in preview. Availability depends on the region's hosted-agent deployment and the feature rollout. Complete the end-to-end verification in this article before relying on a particular subscription and region. Network egress controls are generally available, except for Transform rules, which remain in preview. Using the stable RAI policy API doesn't make Transform rules or secretRef generally available.
secretRef resolution requires access to the Key Vault public endpoint. Resolving secrets through a private endpoint or customer VNet is not supported.
Use valueRef.secretRef in an egress header transform to reference a credential instead of placing its value in your agent image, environment variables, or RAI policy. The egress proxy adds the header to a matching outbound request.
Use a secret reference for an API key or another stored credential. Use valueRef.managedIdentityRef when the destination accepts a Microsoft Entra token. These references use different permission models.
Prerequisites
- A Microsoft Foundry project and hosted agent in an environment that supports secret-backed egress headers.
- Permission to create an agent version. The identity that runs the setup needs the
Microsoft.CognitiveServices/accounts/AIServices/agents/writedata action at the Foundry project. The Foundry User, Foundry Project Manager, and Foundry Owner roles include this permission. See Agent creation. - An RAI policy with egress controls. See Add guardrails to a hosted agent.
- An HTTPS API that you control and that accepts a header-based credential.
- A Foundry project with an enabled system-assigned managed identity (SAMI).
- A container image that the hosted-agent runtime can pull. If the image is in a private registry, the deployed agent identity needs AcrPull on the registry. See Use a private Azure Container Registry.
- Permission to create a disposable Key Vault, write its test secret, and assign secret-read access to the selected runtime identity. These are separate permissions.
- Azure CLI, Bash, and Python 3 for the setup examples. Run the commands in the same shell. Sign in to the intended subscription before continuing.
- Network access from the service's secret-resolution path to the vault, in addition to the agent's outbound access to the API.
- An approved vault network configuration that permits the service to reach the vault's public endpoint. Access from your development machine doesn't prove the secret-resolution service can reach the vault.
Select the runtime identity
For this walkthrough, use the project's SAMI without configuring a different primary identity. You don't need a user-assigned managed identity (UAMI) for this flow. The runtime identity isn't your developer identity, the parent account's identity, or the agent's instance_identity.principal_id. The agent identity in the managed-identity header example has a different purpose: accessing the destination service.
Select the Foundry project that contains the hosted agent. If you need a new project, use Create a Foundry project.
Read the project's identity configuration. Replace the placeholders with the project's Azure Resource Manager resource ID components:
set -euo pipefail subscription_id="<subscription-id>" account_group="<foundry-resource-group>" account_name="<foundry-account-name>" project_name="<foundry-project-name>" account_id="/subscriptions/$subscription_id" account_id="$account_id/resourceGroups/$account_group" account_id="$account_id/providers/Microsoft.CognitiveServices" account_id="$account_id/accounts/$account_name" project_id="$account_id/projects/$project_name" az rest --method get \ --url "$project_id?api-version=2026-09-01" \ --query identity --output jsonReference: Foundry project identity schema.
For a system-assigned project identity,
identity.principalIdis the Microsoft Entra object ID used for role assignments. A client ID, project resource ID, or subscription ID isn't a substitute for this principal ID.Copy your project's SAMI principal ID directly from the project response:
runtime_principal_id=$(az rest --method get \ --url "$project_id?api-version=2026-09-01" \ --query identity.principalId --output tsv) if [ -z "$runtime_principal_id" ] || \ [ "$runtime_principal_id" = "null" ]; then echo "Project SAMI principal ID is missing; stop setup." >&2 exit 1 fi printf '%s\n' "$runtime_principal_id"Reference: Foundry project identity schema.
Confirm the response identifies an enabled system-assigned identity and that the principal ID is populated before continuing. Use this principal ID in the vault grants.
Projects with a configured primary UAMI
This walkthrough doesn't require you to create or switch to a UAMI. If your supported project configuration already selects a primary UAMI for secret resolution, use that identity's principal ID instead of the project's SAMI principal ID. Attaching multiple identities doesn't select one by itself.
Read a confirmed primary UAMI's principal and client IDs from its identity resource:
identity_id="<confirmed-primary-uami-arm-resource-id>"
az identity show --ids "$identity_id" \
--query "{resourceId:id,principalId:principalId,clientId:clientId}" \
--output json
Reference: az identity show.
If this identity is the confirmed selected identity, set runtime_principal_id to its principalId before applying vault grants. Don't use a client ID or Resource Manager resource ID. Don't select an arbitrary attached UAMI or silently fall back to another identity. This walkthrough focuses on the project's SAMI, not on changing its primary identity configuration.
Understand the platform responsibility
You configure the project identity and grant it vault access. Foundry handles identity delegation, registration, and selection for its managed secret-resolution runtime. The service must make the selected project identity available and use that same identity when reading the secret. An identity configured on the project doesn't prove that its runtime registration is complete.
There isn't a customer setup step to discover or choose an identity from a published list of internal sandbox identities. Don't manually patch Foundry's internal sandbox group, attach identities to it, or grant vault access to an arbitrary service identity.
The same customer setup applies to existing and new projects. Foundry owns the runtime identity-registration path; you don't need to repair internal identity metadata. If registration or selection fails, don't recreate the project or its SAMI as a workaround. Contact Azure support with the project ID, request ID, and failure time.
Create the vault and a disposable secret
This walkthrough uses a dedicated test vault with Azure RBAC authorization, a simple string credential, and a versioned secret URI. It doesn't require a Project Connection or promise automatic rotation.
The operator and runtime need different permissions:
| Identity | Permission | Purpose |
|---|---|---|
| Setup operator | Resource-creation permissions and permission to assign Azure roles | Create the test vault and configure access. |
| Setup operator | Key Vault Secrets Officer on the test vault | Write the disposable credential. This role doesn't grant permission to assign roles. |
| Selected runtime identity | Key Vault Secrets User at the vault or secret scope | Read the credential value without granting secret-write permissions. |
Reader and Key Vault Reader don't grant permission to read secret values. Creating a vault or assigning an Azure management role doesn't replace the required secret data-plane permissions. See Azure Key Vault RBAC.
Create a dedicated test resource group and a globally unique vault. Set the subscription explicitly:
vault_group="<test-vault-resource-group>" location="<azure-region>" vault_name="<globally-unique-test-vault-name>" secret_name="hosted-agent-test-key" az group create --subscription "$subscription_id" \ --name "$vault_group" --location "$location" --output none az keyvault create --subscription "$subscription_id" \ --name "$vault_name" --resource-group "$vault_group" \ --location "$location" --enable-rbac-authorization true \ --enable-purge-protection true --output none vault_id=$(az keyvault show --subscription "$subscription_id" \ --name "$vault_name" --resource-group "$vault_group" \ --query id --output tsv)Reference: Create a Key Vault with Azure CLI.
Have an authorized administrator grant the operator secret-write access. Set
operator_object_idto the principal that runs the secret-creation command. For automation, use its service principal's object ID and changeoperator_principal_typetoServicePrincipal.operator_object_id="<operator-principal-object-id>" operator_principal_type="User" az role assignment create --subscription "$subscription_id" \ --assignee-object-id "$operator_object_id" \ --assignee-principal-type "$operator_principal_type" \ --role "Key Vault Secrets Officer" --scope "$vault_id" \ --output noneReference: Assign Azure roles by using Azure CLI.
Allow role-assignment changes to propagate before writing the secret. An authorization failure at this step concerns the operator, not the hosted agent's runtime identity.
Generate a disposable test credential in a restricted temporary file. The command doesn't print the credential or place its value in shell history:
umask 077 credential_file=$(mktemp) trap 'rm -f -- "$credential_file"' EXIT python3 -c \ "import secrets,sys;sys.stdout.write(secrets.token_hex(32))" \ > "$credential_file"Configure your controlled test API to require this credential through its secure administrative setup. Keep the credential out of the agent's image, environment, tool arguments, and source code. Don't use a header-echo endpoint or log the request header.
Store the credential and capture only its versioned URI:
secret_id=$(az keyvault secret set \ --subscription "$subscription_id" \ --vault-name "$vault_name" --name "$secret_name" \ --file "$credential_file" --encoding utf-8 \ --query id --output tsv) printf '%s\n' "$secret_id" rm -f -- "$credential_file" trap - EXITReference: az keyvault secret set.
Copy the returned identifier, in the form
https://<vault>.vault.azure.net/secrets/<name>/<version>. It identifies the version; it isn't the credential value. Don't run the command without the output query, enable shell tracing, or use CLI debug output while handling credentials.
Grant the runtime identity secret access
For the dedicated test vault, assign Key Vault Secrets User to runtime_principal_id, not to an unrelated developer or agent identity:
az role assignment create --subscription "$subscription_id" \
--assignee-object-id "$runtime_principal_id" \
--assignee-principal-type ServicePrincipal \
--role "Key Vault Secrets User" --scope "$vault_id" \
--output none
Reference: Key Vault Azure RBAC permissions.
Secret-read access and permission for the agent to call the destination API are separate requirements.
Vault scope grants reads across this dedicated vault. If your access design requires a single-secret scope, use "$vault_id/secrets/$secret_name" instead. This scope is a Resource Manager scope, not the HTTPS secret URI, and it covers that secret's versions. Don't grant subscription-wide access for this walkthrough.
Allow permission changes to propagate. A successful operator read doesn't prove runtime access; the principals and permissions differ.
Existing access-policy vaults
Use Azure RBAC for new vaults. Legacy access-policy vaults with secret Get permission are also a supported alternative for the pinned-reference flow. For an existing vault that uses this authorization model, grant the selected project identity secret Get permission:
az keyvault set-policy --subscription "$subscription_id" \
--name "$vault_name" --resource-group "$vault_group" \
--object-id "$runtime_principal_id" \
--secret-permissions get --output none
Reference: Assign a Key Vault access policy.
This alternative applies only when the vault uses access policies; it doesn't grant access on an RBAC-authorized vault. Don't switch an existing vault's permission model as a troubleshooting shortcut. The operator separately needs secret Set permission to create the credential under this model.
Add a secret-backed Transform rule
The following egressPolicy object permits calls under api.contoso.com/public/ and replaces their X-Api-Key header with the referenced secret. Other unmatched destinations are denied, apart from required platform connectivity.
Replace the destination host with your controlled API's exact DNS hostname. Set
secretIdto the versioned URI returned insecret_id, including its version segment. Don't substitute a vault Resource Manager resource ID, a versionless URI, or the credential value.Use this object as the
properties.egressPolicyvalue in your RAI policy:{ "mode": "Enforced", "defaultAction": "Deny", "rules": [ { "name": "authenticate-contoso-api", "ruleType": "Fqdn", "match": { "host": "api.contoso.com", "path": "/public/*" }, "action": { "actionType": "Transform", "headers": [ { "operation": "Set", "name": "X-Api-Key", "valueRef": { "secretRef": { "secretId": "https://<vault>.vault.azure.net/secrets/<name>/<version>", "secretKey": "value" } } } ] } } ] }Reference: RAI egress policy and secret reference schema.
Keep the explicit
"secretKey": "value"as shown. The vault secret contains a simple string, not a JSON document. Omitformatbecause the API expects the unchanged key.Merge the egress configuration into your RAI policy deployment. Preserve any content-safety configuration and other rules that the resource needs. The RAI policy must include
contentFilters; creating it without them fails withHTTP 400andContent filters cannot be null.Create or update the RAI policy by using the stable
2026-09-01RAI policy authoring steps. Read back the policy and verify itssecretIdmatches the full pinned URI.Attach the RAI policy by setting
rai_config.rai_policy_nameto its full Resource Manager resource ID when you create a new hosted agent version. Wait until that version is active.Create a fresh session for that version, then verify actual credential injection. Don't reuse a session created before the policy or reference changed.
Successful RAI resource creation alone doesn't verify secret access or injection. Although the schema makes secretKey optional, this walkthrough uses an explicit value; it doesn't demonstrate omission or JSON-property selection.
Call the destination with HTTPS. Use an exact DNS hostname rather than an IP-like source for a credential-bearing Transform rule.
An agent version can reference up to 10 distinct secrets across the egress rules of its attached RAI policy. Rules that use the same versioned secret URI count as one secret. If the policy references more than 10 distinct secrets, creating the version fails with HTTP 400 and the error code invalid_egress_secret_reference.
Choose the header operation and format
Use Set when the referenced credential must replace any value sent by the agent. Insert adds a value only when the header is absent; it doesn't override an agent-supplied value. Remove doesn't use value or valueRef.
For a Set or Insert operation, use valueRef instead of a static value. Keep the reference scoped to the destination that needs the credential.
| Field | Use |
|---|---|
secretId |
Required source identifier. The example uses a versioned Key Vault secret URI. |
format |
Optional formatting around the resolved value, using the {value} placeholder. Omit it for an API key header that needs the secret unchanged. |
secretKey |
Optional in the schema. This walkthrough explicitly uses value and doesn't demonstrate omission or JSON-property selection. |
For an API that expects a bearer credential, use an Authorization header and a format of Bearer {value}. Both secret and managed-identity references use the {value} placeholder.
Reference: RaiEgressSecretRef and RaiEgressManagedIdentityRef.
Runtime Audit mode still applies Transform and Rewrite actions. It isn't a way to test a secret reference without sending a credential. Use a disposable credential and an endpoint that you control.
Add the rule directly to an agent version
The hosted-agent data-plane API also accepts an egress policy directly in the agent definition. This is useful for an API-only qualification test where you don't need to create or reuse an RAI policy. Don't combine an inline policy and an attached RAI policy unless you intend to verify the platform's policy-composition behavior.
PROJECT_ENDPOINT="https://<account>.services.ai.azure.com/api/projects/<project>"
TOKEN=$(az account get-access-token --resource https://ai.azure.com \
--query accessToken --output tsv)
curl -X POST \
"$PROJECT_ENDPOINT/agents/<agent-name>/versions?api-version=v1" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"description": "Secret reference qualification",
"definition": {
"kind": "hosted",
"container_protocol_versions": [
{ "protocol": "responses", "version": "1.0.0" }
],
"cpu": "0.5",
"memory": "1Gi",
"image": "<registry>/<agent-image>:<tag>",
"egress_policy": {
"mode": "enforced",
"rules": [
{
"name": "inject-secret-transform",
"match": {
"host": "api.contoso.com",
"path": "/public/*"
},
"action": {
"type": "transform",
"headers": [
{
"operation": "set",
"name": "X-Api-Key",
"valueRef": {
"secretRef": {
"secretId": "https://<vault>.vault.azure.net/secrets/<name>/<version>",
"secretKey": "value"
}
}
}
]
}
}
]
}
}
}'
Treat the version POST and subsequent provisioning status as separate checks:
- POST succeeds: the request accepted the agent and egress-policy shape.
- Version becomes active: the platform resolved and provisioned the referenced secret and pulled the image.
- Fresh session call succeeds: the egress proxy injected the credential for a matching outbound request.
If the inline version request returns 404 or 500 before an agent version is created, validate that the hosted-agent API is deployed and routed in the region. That failure occurs before secret-reference resolution and isn't evidence of an invalid Key Vault reference.
Verify credential injection
Check secret resolution, injection, and network restrictions independently. A successful agent response or a policy-compliance result doesn't establish all three.
- Confirm that the version create operation succeeded and the version reports
active, then start a fresh test session using that exact version. - Have the agent make an HTTPS request under the approved
/public/path without supplying the credential itself. - Confirm from the controlled API's authentication result that it received the expected credential. An agent's text saying the request succeeded isn't sufficient. Record only the authentication outcome and a request correlation ID; don't log or return the credential.
- To check
Setbehavior, send a harmless, incorrectX-Api-Keysentinel from the agent. Confirm that the API still authenticates the request because the proxy replaced the sentinel. Never give the real credential to the agent for this check. - Make a request to an unapproved destination and verify the runtime denial.
- Verify that the application configuration doesn't separately contain the same credential in environment variables, files, or image layers.
- In a separate disposable configuration, reference a nonexistent secret version or an identity without access. Confirm the operation reports a failure rather than treating injection as successful.
Secret-reference provisioning can fail while creating a version, before a session exists. Separate that failure from a later network denial or a destination API authentication failure. Capture the request ID and failing operation, not secret contents. The same HTTP status alone doesn't identify the cause.
If Azure Policy assignments apply, allow for policy propagation before verifying governance compliance and authoring behavior. A value reference can satisfy a configuration requirement while access to the referenced secret still fails.
Plan credential rotation
A versioned Key Vault URI identifies one version. Creating a newer vault version doesn't change the version named by that URI.
To select a different pinned version, update the reference and follow the supported agent-version and session lifecycle. Don't assume that updating the RAI resource immediately replaces credentials in running sessions.
The baseline here is pinned references. It doesn't establish unversioned refresh intervals, automatic rotation, or a credential-revocation deadline. For a new credential version, create a new pinned reference, deploy a new hosted-agent version, start a fresh session, and repeat the authentication check. Validate revocation separately; don't assume an existing session reloads changes.
Configure secret references in the portal
If secret-reference authoring is available in your environment, configure the same rule through the guardrail's Network control. A visible field doesn't establish runtime support; verify injection after saving.
In the Foundry portal, create or edit the guardrail. Expand Network, select Egress rules, and then select Add rules.
Select Enforce. Set Host match to your API's DNS hostname and Path to its approved path. To match the JSON example in this article, use
api.contoso.comand/public/*.Select Transform for Action. Enter
X-Api-Keyfor Header name, select Set for Operation, and select Secret reference for Value source.The screenshot shows a demo
/v1/orderspath before you enter the secret reference fields or save the rule.Enter the full versioned secret URI in Secret ID. Set Secret Key (Optional) to
value, matching the walkthrough's explicitsecretKey. Leave Format (Optional) empty for the unchanged API key. Placeholder text in an empty field isn't a configured value.Select Add to add the rule, and then select Create to save the egress rules. Finish saving the guardrail.
Attach the guardrail to a new hosted-agent version, start a fresh session, and verify actual credential injection.
Clean up test resources
After a successful verification, delete the test resources in this order:
- Delete the test session.
- Delete the test agent or agent version.
- Remove the temporary role assignments.
- Delete and purge the disposable Key Vault according to your organization's retention policy.
- Delete the controlled test API and any temporary supporting infrastructure.
If any step fails, retain the project, vault, agent version, request IDs, and correlation IDs until the issue is investigated. Don't delete evidence from a failed region merely because another region passed.
Troubleshoot secret references
Use the failure stage and request ID to identify the problem. Keep secret values out of diagnostic output.
| Symptom | Check |
|---|---|
| Agent creation is forbidden before secret processing. | The caller must have the Microsoft.CognitiveServices/accounts/AIServices/agents/write data action at the Foundry project. Azure Owner and Contributor alone don't include this data-plane permission. |
| The version fails with an image or registry error. | Confirm that the deployed agent identity has AcrPull on a private registry. This is separate from Key Vault and egress permissions. |
| Identity registration or selection fails, including "Managed identity is not attached." | Foundry's secret-resolution runtime couldn't select an available identity. Confirm the project's intended identity and contact Azure support. This error isn't the same as a Key Vault permission denial. Don't recreate the project or its SAMI, patch an internal sandbox group, or grant broader vault permissions as a workaround. |
| Key Vault denies the selected identity's secret read. | Confirm the principal/object ID and the vault's authorization model. Use Key Vault Secrets User for RBAC or secret Get for an access-policy vault. Reader is insufficient. A successful operator read proves only the operator's access. |
| The secret-resolution service can't reach the vault. | Check public-endpoint access, DNS, and firewall rules for the service-to-vault path. Resolving through a private endpoint or customer VNet is not supported. Reachability from the agent or your machine doesn't prove resolver reachability. |
| The secret or pinned version isn't found or is disabled. | Check the exact vault, secret name, version, and enabled state. A missing version differs from identity-registration or authorization failure. |
| An unversioned URI or Project Connection reference is rejected. | This walkthrough uses only the pinned Key Vault reference shape. Don't infer other source or rotation support from the schema. |
The version POST returns 404 or 500 before a version is created. |
Confirm that the hosted-agent Agents API is deployed and available in that region. This failure occurs before secret-resolution code runs. Capture the APIM request ID and contact Azure support or the service owner. |
| Version creation fails with "An agent version can reference at most 10 distinct egress secrets." | The attached RAI policy references more than 10 distinct secrets. Reduce the distinct secret references to 10 or fewer. |
The agent version is created and becomes active, but every session fails with HTTP 500 session_creation_failed. |
Check the project's region and hosted-agent deployment status. A policy can be accepted during authoring even when the runtime deployment doesn't support secretRef. Capture the request ID and verify the feature through a controlled fresh-session request. |
| The API rejects the credential. | Check the selected version, header name, expected format, and whether Insert preserved a different application-supplied header. |
| The request is blocked before the API receives it. | Check the effective egress rules and destination. Secret access doesn't permit outbound traffic by itself. |
| An update doesn't change an active session's credential. | Check the documented rotation and session lifecycle. Don't treat a vault update as immediate session revocation. |