Azure AI Foundry with Entra ID
Call Claude models in Azure AI Foundry as the signed-in user with the Microsoft Entra on-behalf-of flow.
Call Claude models in Azure AI Foundry with the permissions of the signed-in user. The gateway uses the Microsoft Entra ID on-behalf-of (OBO) flow to get a delegated access token for Azure Cognitive Services.
About
The gateway app needs no Azure role on the Foundry resource. A request follows these steps.
- The client signs in the user and sends the gateway an access token issued for the gateway app.
- The gateway validates the token with the tenant’s signing keys. If the gateway has no cached token for this exchange, it requests one from Entra ID.
- The gateway forwards the request to Foundry with the delegated token in the
Authorizationheader. Foundry checks the user’s role on the resource.
The gateway reuses a cached token until shortly before either token expires. The gateway validates user tokens locally. A user whose sign-in you block in Entra ID might still be able to use an existing token.
Entra ID settings
Use the JWT bearer grant with these Entra and Foundry settings.
| Field | Value for Entra ID |
|---|---|
url | The HTTPS token endpoint for your tenant, https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token. |
grantType | JwtBearer. The gateway sends the user’s token as the assertion parameter. |
scopes | https://cognitiveservices.azure.com/user_impersonation, the delegated permission for Azure Cognitive Services. |
clientAuth | The client ID and the client secret of the gateway app. Set method to ClientSecretPost. |
additionalParams | requested_token_use: '"on_behalf_of"'. Values in additionalParams are CEL expressions, so the literal string is quoted. |
Supported requests
Use this configuration for Claude Messages, including streaming, and token counting. The example uses the resource-level Anthropic endpoints. OpenAI-compatible inference and Foundry Agent Service are outside the scope of this guide.
Before you begin
Follow the Get started guide to install agentgateway.
Follow the Sample app guide to create a gateway proxy with an HTTP listener and deploy the httpbin sample app.
Get the external address of the gateway and save it in an environment variable.
Tip
Kind cluster? Kind does not support
LoadBalancerservices by default. To use this option with a Kind cluster, install and runcloud-provider-kind.export INGRESS_GW_ADDRESS=$(kubectl get svc -n agentgateway-system agentgateway-proxy -o jsonpath="{.status.loadBalancer.ingress[0]['hostname','ip']}") echo $INGRESS_GW_ADDRESS
Deploy a Claude model in Azure AI Foundry. Choose a deployment name that starts with
claudeso the gateway selects the Anthropic API paths.Sign in to the Azure CLI. You need permission to manage app registrations and grant tenant consent. To create the example role, you also need permission to create role definitions in the subscription and assign roles on the Foundry resource.
Set the resource, project, and deployment names.
export FOUNDRY_RESOURCE=<foundry-resource-name> export FOUNDRY_PROJECT=<foundry-project-name> export FOUNDRY_MODEL=<claude-deployment-name>
Step 1: Register the gateway and client apps in Entra ID
Register the gateway as an API that clients can call. Give the gateway app permission to request a delegated Cognitive Services token.
In the Azure portal, go to Microsoft Entra ID > App registrations > New registration. Enter a name such as
agentgateway, select Accounts in this organizational directory only, and select Register.Save the application (client) ID and the directory (tenant) ID as environment variables.
export ENTRA_TENANT_ID=<directory-tenant-id> export ENTRA_CLIENT_ID=<application-client-id>Go to Manifest. Set
requestedAccessTokenVersionto2and select Save. Entra ID then issues v2.0 tokens, which the JWT authentication policy in Step 4 expects.Go to Expose an API. Add the application ID URI and keep the default value
api://<application-client-id>. Then, add a scope that is namedaccessand set Who can consent to Admins and users.Go to API permissions > Add a permission > APIs my organization uses. Search for Microsoft Cognitive Services and select the user_impersonation delegated permission.
Select Grant admin consent for your organization. Verify that user_impersonation shows Granted.
Go to Certificates & secrets and add a client secret. Save the value as an environment variable. The portal shows the value only one time.
export ENTRA_CLIENT_SECRET=<client-secret-value>Open or register the client app your users sign in to. Under API permissions, add the gateway app’s delegated
accesspermission.In the gateway app, open Expose an API. Add the client app’s ID under Authorized client applications and select the
accessscope.
Step 2: Give users access to Azure AI Foundry
Assign the following role to a group of users on the Foundry resource. The role grants the provider-model data action that Claude inference requires.
Save the following role definition to a
foundry-user-inference-role.jsonfile. Replace<subscription-id>with the ID of your Azure subscription.{ "Name": "Foundry Claude Inference", "IsCustom": true, "Description": "Claude inference on Azure AI Foundry with no control plane access.", "Actions": [], "NotActions": [], "DataActions": [ "Microsoft.CognitiveServices/accounts/AIServices/providers/action" ], "NotDataActions": [], "AssignableScopes": ["/subscriptions/<subscription-id>"] }The role grants no control-plane permissions. For the data actions that other inference APIs require, see Use a least-privilege role for Azure AI Foundry.
Create the role and assign it to the group. Use the Foundry resource as the assignment scope because the Claude endpoints are resource-level paths.
az role definition create --role-definition foundry-user-inference-role.json FOUNDRY_ID=$(az cognitiveservices account show \ --name $FOUNDRY_RESOURCE --resource-group <resource-group> --query id -o tsv) az role assignment create \ --assignee-object-id <user-group-object-id> --assignee-principal-type Group \ --role "Foundry Claude Inference" --scope "$FOUNDRY_ID"A new role assignment can take a few minutes to take effect.
Step 3: Restrict network access to Foundry
A user with the inference role can also call Foundry directly. To require access through the gateway, restrict which clients can reach the Foundry endpoint.
Turn off API key authentication on the resource. All requests must then use an Entra ID token.
az resource update --ids "$FOUNDRY_ID" --set properties.disableLocalAuth=trueChoose a network configuration for the Foundry resource.
- Private endpoint. Create a private endpoint reachable from the gateway, configure private DNS, and disable public network access. Restrict access to the private endpoint to the gateway. Other clients with network access to the endpoint can also reach Foundry.
- Public endpoint with an IP allowlist. Deny traffic by default and allow the gateway’s outbound IP addresses. Use dedicated addresses if only the gateway should have access.
For setup instructions, see Configure virtual networks for Azure AI services.
Step 4: Configure agentgateway
Create the backend with the token exchange, the route, and the policy that validates the user’s token.
Create a Kubernetes Secret with the client secret of the gateway app. The backend reads the secret from the
clientSecretkey.kubectl create secret generic foundry-obo-client \ -n agentgateway-system \ --from-literal=clientSecret="${ENTRA_CLIENT_SECRET}"Create the Foundry backend and an HTTPRoute that forwards requests under
/foundryto it.kubectl apply -f- <<EOF apiVersion: agentgateway.dev/v1alpha1 kind: AgentgatewayBackend metadata: name: foundry namespace: agentgateway-system spec: ai: provider: azure: resourceName: ${FOUNDRY_RESOURCE} resourceType: Foundry projectName: ${FOUNDRY_PROJECT} model: ${FOUNDRY_MODEL} policies: ai: routes: /v1/messages: Messages /v1/messages/count_tokens: AnthropicTokenCount auth: oauthTokenExchange: url: https://login.microsoftonline.com/${ENTRA_TENANT_ID}/oauth2/v2.0/token grantType: JwtBearer scopes: - https://cognitiveservices.azure.com/user_impersonation clientAuth: clientId: ${ENTRA_CLIENT_ID} method: ClientSecretPost secretRef: name: foundry-obo-client additionalParams: requested_token_use: '"on_behalf_of"' --- apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: foundry namespace: agentgateway-system spec: parentRefs: - name: agentgateway-proxy namespace: agentgateway-system rules: - matches: - path: type: PathPrefix value: /foundry filters: - type: URLRewrite urlRewrite: path: type: ReplacePrefixMatch replacePrefixMatch: / backendRefs: - group: agentgateway.dev kind: AgentgatewayBackend name: foundry EOFSetting Description azure.resourceTypeSet to Foundryfor the<resource-name>.services.ai.azure.comendpoint.azure.modelOverrides the model in the request with the deployment name. policies.ai.routesSelects the Anthropic Messages and token count APIs for the two request paths. policies.auth.oauthTokenExchangeUses the delegated token for backend authentication. See Entra ID settings. URLRewriteRemoves the /foundryprefix so that a request to/foundry/v1/messagesmatches the/v1/messagesroute.Create a JWT authentication policy on the route. The policy gets the signing keys of your tenant from Entra ID.
kubectl apply -f- <<EOF apiVersion: agentgateway.dev/v1alpha1 kind: AgentgatewayPolicy metadata: name: foundry-jwt namespace: agentgateway-system spec: targetRefs: - group: gateway.networking.k8s.io kind: HTTPRoute name: foundry traffic: jwtAuthentication: mode: Strict preserveToken: true providers: - issuer: https://login.microsoftonline.com/${ENTRA_TENANT_ID}/v2.0 audiences: - ${ENTRA_CLIENT_ID} jwks: remote: url: https://login.microsoftonline.com/${ENTRA_TENANT_ID}/discovery/v2.0/keys EOFSetting Description mode: StrictRejects a request without a valid token with a 401response.preserveTokenKeeps the validated token in the Authorizationheader for the exchange.issuerMatches v2.0 tokens issued by your Entra tenant for the gateway app. audiencesThe client ID of the gateway app. Check the backend and policy status. Expect
Acceptedfor the backend andValidfor the policy.kubectl get AgentgatewayBackend foundry -n agentgateway-system \ -o jsonpath='{.status.conditions[0].reason}{"\n"}' kubectl get AgentgatewayPolicy foundry-jwt -n agentgateway-system \ -o jsonpath='{.status.ancestors[0].conditions[0].reason}{"\n"}'Example output:
Accepted Valid
Step 5: Verify the exchange
Test with a user who belongs to the group from Step 2.
Sign in to the client app. Request the
api://<gateway-app-client-id>/accessscope and save the access token. For client libraries, see the Microsoft Authentication Library overview.export USER_TOKEN=<user-access-token>Set the URL for your gateway.
Add an HTTPS listener to the
agentgateway-proxyGateway used by the Foundry route. Set the URL to the listener’s hostname and port. Use a certificate your client trusts.export GATEWAY_URL="https://<gateway-hostname>:<https-port>"Send a Messages request. Look for HTTP
200and a Claude message in the response body.curl -si "$GATEWAY_URL/foundry/v1/messages" \ -H "Authorization: Bearer ${USER_TOKEN}" \ -H "Content-Type: application/json" \ -d '{"model":"'"${FOUNDRY_MODEL}"'","max_tokens":256,"messages":[{"role":"user","content":"Hello"}]}'Repeat the request without the
Authorizationheader. The gateway returns HTTP401with the bodyauthentication failedbefore attempting an exchange.
Troubleshooting
To see why Entra ID rejected an exchange, enable debug logging for the token exchange module on the proxy.
kubectl port-forward deployment/agentgateway-proxy -n agentgateway-system 15000 &
curl -X POST "http://localhost:15000/logging?level=info,agentgateway::http::auth::oauth=debug"Repeat the request, then read the proxy logs. The debug entry includes the token endpoint’s response.
kubectl logs deployment/agentgateway-proxy -n agentgateway-system | grep "oauth token exchange"Use the response and the log entry to identify the next step.
| Symptom | Cause | Fix |
|---|---|---|
401 authentication failed from the gateway | The user token is missing or failed validation. | Request the gateway app’s access scope. Check the issuer, audience, and expiration. |
400 invalid request and AADSTS65001 in the proxy log | Entra ID requires consent. | Check tenant consent for the delegated permission in Step 1. |
500 backend authentication failed and a token endpoint 401 or 403 in the proxy log | Entra ID rejected the gateway’s token request. | Check the client ID and the clientSecret key in the foundry-obo-client Secret. |
401 response with a PermissionDenied error from Azure AI Foundry | Either the user has no role on the Azure AI Foundry resource or the role assignment is new. | Assign the role, as described in Step 2. Wait a few minutes. |
| A Messages request returns an OpenAI-format response | The gateway used the default chat completions route. | Check the policies.ai.routes map and the /foundry prefix rewrite in Step 4. |
The backend shows PartiallyValid | The Secret is missing or has no clientSecret key. | Create or correct the Secret. The controller reconciles the backend automatically. |
The gateway gets a 403 response from Azure AI Foundry | Either the gateway is not on an allowed network or the gateway resolves the resource to a public IP address. | Check the network rules and the private DNS setup from Step 3. |
Cleanup
You can remove the resources that you created in this guide.Delete the Kubernetes resources.
kubectl delete AgentgatewayPolicy foundry-jwt -n agentgateway-system kubectl delete httproute foundry -n agentgateway-system kubectl delete AgentgatewayBackend foundry -n agentgateway-system kubectl delete secret foundry-obo-client -n agentgateway-systemIf you enabled debug logging, restore your previous proxy log level and stop the admin port-forward.
Remove the role assignment, custom role, client secret, and app registrations you created solely for this guide.