Skip to content
Help guide the future of agentgateway — Take the survey

Azure AI Foundry with Entra ID

Page as Markdown

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.

  1. The client signs in the user and sends the gateway an access token issued for the gateway app.
  2. 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.
  3. The gateway forwards the request to Foundry with the delegated token in the Authorization header. 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.

FieldValue for Entra ID
urlThe HTTPS token endpoint for your tenant, https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token.
grantTypeJwtBearer. The gateway sends the user’s token as the assertion parameter.
scopeshttps://cognitiveservices.azure.com/user_impersonation, the delegated permission for Azure Cognitive Services.
clientAuthThe client ID and the client secret of the gateway app. Set method to ClientSecretPost.
additionalParamsrequested_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

  1. Follow the Get started guide to install agentgateway.

  2. Follow the Sample app guide to create a gateway proxy with an HTTP listener and deploy the httpbin sample app.

  3. Get the external address of the gateway and save it in an environment variable.

    Tip

    Kind cluster? Kind does not support LoadBalancer services by default. To use this option with a Kind cluster, install and run cloud-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  

  1. Deploy a Claude model in Azure AI Foundry. Choose a deployment name that starts with claude so the gateway selects the Anthropic API paths.

  2. 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.

  3. 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.

  1. 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.

  2. 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>
  3. Go to Manifest. Set requestedAccessTokenVersion to 2 and select Save. Entra ID then issues v2.0 tokens, which the JWT authentication policy in Step 4 expects.

  4. 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 named access and set Who can consent to Admins and users.

  5. Go to API permissions > Add a permission > APIs my organization uses. Search for Microsoft Cognitive Services and select the user_impersonation delegated permission.

  6. Select Grant admin consent for your organization. Verify that user_impersonation shows Granted.

  7. 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>
  8. Open or register the client app your users sign in to. Under API permissions, add the gateway app’s delegated access permission.

  9. In the gateway app, open Expose an API. Add the client app’s ID under Authorized client applications and select the access scope.

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.

  1. Save the following role definition to a foundry-user-inference-role.json file. 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.

  2. 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.

  1. 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=true
  2. Choose 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.

  1. Create a Kubernetes Secret with the client secret of the gateway app. The backend reads the secret from the clientSecret key.

    kubectl create secret generic foundry-obo-client \
      -n agentgateway-system \
      --from-literal=clientSecret="${ENTRA_CLIENT_SECRET}"
  2. Create the Foundry backend and an HTTPRoute that forwards requests under /foundry to 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
    EOF
    SettingDescription
    azure.resourceTypeSet to Foundry for the <resource-name>.services.ai.azure.com endpoint.
    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 /foundry prefix so that a request to /foundry/v1/messages matches the /v1/messages route.
  3. 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
    EOF
    SettingDescription
    mode: StrictRejects a request without a valid token with a 401 response.
    preserveTokenKeeps the validated token in the Authorization header for the exchange.
    issuerMatches v2.0 tokens issued by your Entra tenant for the gateway app.
    audiencesThe client ID of the gateway app.
  4. Check the backend and policy status. Expect Accepted for the backend and Valid for 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.

  1. Sign in to the client app. Request the api://<gateway-app-client-id>/access scope and save the access token. For client libraries, see the Microsoft Authentication Library overview.

    export USER_TOKEN=<user-access-token>
  2. Set the URL for your gateway.

    Add an HTTPS listener to the agentgateway-proxy Gateway 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>"
  3. Send a Messages request. Look for HTTP 200 and 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"}]}'
  4. Repeat the request without the Authorization header. The gateway returns HTTP 401 with the body authentication failed before 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.

SymptomCauseFix
401 authentication failed from the gatewayThe 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 logEntra 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 logEntra 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 FoundryEither 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 responseThe gateway used the default chat completions route.Check the policies.ai.routes map and the /foundry prefix rewrite in Step 4.
The backend shows PartiallyValidThe 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 FoundryEither 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.
  1. 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-system
  2. If you enabled debug logging, restore your previous proxy log level and stop the admin port-forward.

  3. Remove the role assignment, custom role, client secret, and app registrations you created solely for this guide.

Was this page helpful?
Agentgateway assistant

Ask me anything about agentgateway configuration, features, or usage.

Note: AI-generated content might contain errors; please verify and test all returned information.

Tip: one topic per conversation gives the best results. Use the + button in the chat header to start a new conversation.

Switching topics? Starting a new conversation improves accuracy.
↑↓ navigate ↵ select esc dismiss

What could be improved?

Your feedback helps us improve assistant answers and identify docs gaps we should fix.

Need more help? Join us on Discord: https://discord.gg/y9efgEmppm

Want to use your own agent? Add the Solo MCP server to query our docs directly. Get started here: https://search.solo.io/.