{"slug": "add-entra-id-sign-in-to-codex-cli-through-agentgateway-part-2", "title": "Add Entra ID Sign-In to Codex CLI Through agentgateway (Part 2)", "summary": "A follow-up post to a two-part series documents adding Microsoft Entra ID sign-in to Codex CLI 0.170.0 through open source agentgateway v1.7.0, closing a hole from Part 1 in which the gateway accepted requests from anyone who could reach its port. The setup requires an Entra app registration that issues tokens carrying the user's group IDs, an agentgateway policy that validates the token's signature, issuer, audience and membership in a `codex` group, and a Codex profile that points users to the Microsoft sign-in page; the gateway returns 401 for requests without a token and 403 for users outside the group. The configuration covers both the `/v1` Bedrock route and the `/mcp` Solo.io docs search server, with full commands in the sebbycorp/agentgateway-oss-k8s repository.", "body_md": "In [Part 1](https://agentgateway.dev/blog/2026-11-18-deploy-codex-cli-bedrock-agentgateway/) I put Codex CLI behind open source agentgateway so it could use an OpenAI model on Amazon Bedrock without holding a key. That left one obvious hole: the gateway took requests from anyone who could reach the port.\n\nThis post closes it. When I type `codex` now, it sends me to the Microsoft sign-in page first. The gateway only accepts my requests if I come back with an Entra ID token **and** I am in the `codex` group.\n\nWhat you end up with:\n\n`codex` group, or the gateway answers 403.`/v1` (Bedrock) and `/mcp` (the Solo.io docs search server).\nAll of it is open source agentgateway v1.7.0 and Codex CLI 0.170.0. The full step list with every command is in the repo: [sebbycorp/agentgateway-oss-k8s, entra-id/README.md](https://github.com/sebbycorp/agentgateway-oss-k8s/blob/main/entra-id/README.md).\n\n``` php\nflowchart LR\nU[You type codex] --> C[Codex CLI]\nC -- \"1. no sign-in yet: open browser\" --> E[Microsoft Entra ID]\nE -- \"2. token with your group IDs\" --> C\nC -- \"3. Authorization: Bearer token\" --> G[agentgateway proxy]\nG -- \"valid token + codex group\" --> B[Amazon Bedrock]\nG -- \"valid token + codex group\" --> M[search.solo.io MCP]\nG -. \"no token: 401, wrong group: 403\" .-> C\n```\n\nThree parts have to agree:\n\n| Part | What it does | \n|---|---|\n| Entra app registration | Issues tokens for “the gateway”, with the user’s group IDs inside | \n| agentgateway policy | Checks the token’s signature, issuer, audience and group | \n| Codex profile | Tells Codex where to send the user to sign in | \n\n`solo-search` MCP route and a Codex profile.\n\n```\naz login\nexport TENANT_ID=$(az account show --query tenantId -o tsv)\nexport CTX=kind-agentgateway-codex\nexport GROUP_ID=$(az ad group create --display-name codex --mail-nickname codex \\\n --description \"Access to LLMs and MCP servers through agentgateway\" --query id -o tsv)\n\naz ad group member add --group $GROUP_ID \\\n --member-id $(az ad signed-in-user show --query id -o tsv)\n```\n\nThe app registration stands for the gateway. The gateway accepts only tokens that were issued for this app.\n\n```\nexport APP_ID=$(az ad app create --display-name agentgateway-oss-codex \\\n --sign-in-audience AzureADMyOrg --query appId -o tsv)\nOBJECT_ID=$(az ad app show --id $APP_ID --query id -o tsv)\n\n# Application ID URI, and put the user's security groups in the token\naz ad app update --id $APP_ID --identifier-uris \"api://$APP_ID\" \\\n --set groupMembershipClaims=SecurityGroup\n\n# Expose one scope (\"access\") and issue v2.0 tokens\nSCOPE_ID=$(uuidgen | tr 'A-Z' 'a-z')\naz rest --method PATCH --uri \"https://graph.microsoft.com/v1.0/applications/$OBJECT_ID\" \\\n --headers 'Content-Type=application/json' --body \"{\n \\\"api\\\": {\n \\\"requestedAccessTokenVersion\\\": 2,\n \\\"oauth2PermissionScopes\\\": [{\n \\\"id\\\": \\\"$SCOPE_ID\\\", \\\"value\\\": \\\"access\\\", \\\"type\\\": \\\"User\\\", \\\"isEnabled\\\": true,\n \\\"adminConsentDisplayName\\\": \\\"Access agentgateway\\\",\n \\\"adminConsentDescription\\\": \\\"Call LLMs and MCP servers through agentgateway\\\",\n \\\"userConsentDisplayName\\\": \\\"Access agentgateway\\\",\n \\\"userConsentDescription\\\": \\\"Call LLMs and MCP servers through agentgateway\\\"\n }]\n }\n }\"\n\n# Public client (no secret) with loopback redirect URIs, so Codex can finish the sign-in\naz rest --method PATCH --uri \"https://graph.microsoft.com/v1.0/applications/$OBJECT_ID\" \\\n --headers 'Content-Type=application/json' --body '{\n \"isFallbackPublicClient\": true,\n \"publicClient\": { \"redirectUris\": [\"http://127.0.0.1/callback\", \"http://localhost/callback\"] }\n }'\n\naz ad sp create --id $APP_ID\n```\n\nFour settings matter here, and each one fails in its own way if you skip it:\n\n| Setting | If you skip it | \n|---|---|\n| Scope `api://<APP_ID>/access` | Codex has nothing to ask a token for | \n| `requestedAccessTokenVersion: 2` | Sign-in works, but the gateway answers 401 because the issuer is the old v1 one | \n| `groupMembershipClaims: SecurityGroup` | The token has no groups, so the gateway answers 403 | \n| Public client redirect URIs | The browser shows `AADSTS500113: No reply address is registered` | \n\nI hit the last one myself. I ran Codex before adding the redirect URIs and got the `AADSTS500113` page.\n\nTwo policies, in [`k8s/06-entra-auth.yaml`](https://github.com/sebbycorp/agentgateway-oss-k8s/blob/main/k8s/06-entra-auth.yaml). The first one attaches to the Gateway and covers everything:\n\n```\napiVersion: agentgateway.dev/v1alpha1\nkind: AgentgatewayPolicy\nmetadata:\n name: entra-auth\n namespace: agentgateway-system\nspec:\n targetRefs:\n - group: gateway.networking.k8s.io\n kind: Gateway\n name: agentgateway-proxy\n traffic:\n jwtAuthentication: # who are you? 401 if the token is missing or invalid\n mode: Strict\n providers:\n - issuer: https://login.microsoftonline.com/${TENANT_ID}/v2.0\n audiences:\n - ${APP_ID}\n jwks:\n remote:\n url: https://login.microsoftonline.com/${TENANT_ID}/discovery/v2.0/keys\n authorization: # are you allowed? 403 if not in the group\n action: Allow\n policy:\n matchExpressions:\n - '\"${GROUP_ID}\" in jwt.groups'\n```\n\nThe second one attaches to the MCP route. It repeats the same checks and adds one block:\n\n```\n mcp:\n provider: Entra  # bridges the gaps between Entra and the MCP auth spec\n clientId: ${APP_ID}  # Entra has no dynamic client registration\n resourceMetadata:\n scopesSupported:\n - api://${APP_ID}/access\n bearerMethodsSupported:\n - header\n```\n\nThat block makes the gateway serve the OAuth discovery endpoints an MCP client looks for. Entra does not follow the MCP authorization spec on its own, and agentgateway’s `Entra` provider fills the gaps.\n\nThe MCP route also needs two extra path matches so those discovery requests reach it. Without them the gateway answered `route not found` on `/.well-known/oauth-protected-resource/mcp`:\n\n```\n - path:\n type: PathPrefix\n value: /.well-known/oauth-protected-resource\n - path:\n type: PathPrefix\n value: /.well-known/oauth-authorization-server\n```\n\nApply both files. The IDs are filled in at apply time, so they stay out of the repo:\n\n```\nkubectl --context $CTX apply -f k8s/05-mcp-solo-search.yaml\n\nsed -e \"s/\\${TENANT_ID}/$TENANT_ID/g\" -e \"s/\\${APP_ID}/$APP_ID/g\" -e \"s/\\${GROUP_ID}/$GROUP_ID/g\" \\\n k8s/06-entra-auth.yaml | kubectl --context $CTX apply -f -\n```\n\nI tested the gateway with curl first, so I knew the policy worked before adding a second moving part.\n\n| Request | LLM `/v1` | MCP `/mcp` | \n|---|---|---|\n| No token | 401 | 401 | \n| Garbage token | 401 | 401 | \n| Valid Entra token for a different API | 401 | not tested | \n| Valid token, group not matching | 403 | 403 | \n| Valid token, user in the group | 200 | 200 | \n\nFor the “group not matching” row I pointed the policy at a group ID that does not exist. I did not test with a second real user.\n\nCodex CLI has a `gateway_oauth` table on a model provider. Give it the Entra endpoints and the app’s client ID:\n\n```\nmodel = \"gpt-oss-120b\"\nmodel_provider = \"agentgateway\"\n\n[model_providers.agentgateway]\nname = \"agentgateway\"\nbase_url = \"http://localhost:<port>/v1\"\nwire_api = \"responses\"\n\n# Codex signs you in with Microsoft Entra ID before it calls the gateway.\n[model_providers.agentgateway.gateway_oauth]\nauthorization_url = \"https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/authorize\"\ntoken_url = \"https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/token\"\nclient_id = \"<APP_ID>\"\nscopes = [\"api://<APP_ID>/access\", \"offline_access\"]\n\n[mcp_servers.solo-search]\nurl = \"http://localhost:<port>/mcp\"\n```\n\nSave it as `~/.codex/agentgateway.config.toml`. There is no token and no secret in the file. If you added the two blocks that make Claude models work in the [previous post](https://agentgateway.dev/blog/2026-11-18-deploy-codex-cli-bedrock-agentgateway/#10-more-models-optional), keep them at the end of the file.\n\nNow start Codex:\n\n```\ncodex --profile agentgateway\n```\n\nCodex opens the Microsoft page. If it cannot open a browser, it prints the link:\n\n```\nAuthorize the model provider by opening this URL:\nhttps://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/authorize?response_type=code&client_id=...\n```\n\nAfter the sign-in Codex continues, and it keeps the token encrypted under `~/.codex/secrets/`. It refreshes the token by itself, so the next run does not ask again.\n\nThe MCP server does not reuse the model sign-in. It has its own, and this is the part that took the longest to get right.\n\nCodex adds an ID to the end of its MCP callback path, and Entra matches redirect paths exactly. So you have to find that ID and register it. Print the path:\n\n```\ncodex --profile agentgateway mcp login solo-search --no-browser </dev/null 2>&1 \\\n | grep -oE 'redirect_uri=[^&]+' | python3 -c \"import sys, urllib.parse as u; print(u.unquote(sys.stdin.read()))\"\n# redirect_uri=http://127.0.0.1:63884/callback/dFBqJtJnaDT6\n```\n\nRegister it on the app, without the port:\n\n```\nCALLBACK_ID=dFBqJtJnaDT6 # yours will differ\naz rest --method PATCH --uri \"https://graph.microsoft.com/v1.0/applications/$OBJECT_ID\" \\\n --headers 'Content-Type=application/json' --body \"{\n \\\"publicClient\\\": { \\\"redirectUris\\\": [\n \\\"http://127.0.0.1/callback\\\", \\\"http://localhost/callback\\\",\n \\\"http://127.0.0.1/callback/$CALLBACK_ID\\\"\n ] }\n }\"\n```\n\nThen sign in:\n\n```\ncodex --profile agentgateway mcp login solo-search\n# Successfully logged in to MCP server 'solo-search'.\n```\n\nThe ID is derived from the MCP server URL. It stayed the same when I renamed the server and changed when I changed the host in the URL. So if your gateway address changes, you redo this step.\n\n```\necho 'alias codex=\"codex --profile agentgateway\"' >> ~/.zshrc\nsource ~/.zshrc\n```\n\nI used an alias instead of editing `~/.codex/config.toml`, because that file is shared with the ChatGPT desktop app.\n\nTo prove the sign-in is enforced, I moved the stored credential away and started Codex. It stopped and printed the sign-in link again. With the credential back, it ran:\n\n```\ncodex exec --skip-git-repo-check \\\n \"Use the solo-search MCP search tool to look up: agentgateway. Reply with the top result's title only.\"\n# mcp: solo-search/search started\n# mcp: solo-search/search (completed)\n# What is agentgateway and why do I want to use it?\n```\n\nOut of the box the request log identifies the user by the token’s `sub` claim, which is an opaque string. One setting changes it to the sign-in name:\n\n```\nkubectl --context $CTX -n agentgateway-system patch agentgatewayparameters agentgateway-proxy-params \\\n --type merge -p '{\"spec\":{\"rawConfig\":{\"config\":{\"standardAttributes\":{\"user\":\"jwt.preferred_username\"}}}}}'\n```\n\nI also turned on prompt logging, which stores the prompt and the answer of every call. On Kubernetes the checkbox for it in the UI is read-only, so it goes in the proxy parameters:\n\n```\nspec:\n rawConfig:\n frontendPolicies:\n accessLog:\n database:\n llm: full\n```\n\nThe Logs page now shows the prompt on each row:\n\nAnd the user, the group and the whole conversation when you open one (I blurred the user and group here):\n\nThink before you turn prompt logging on for a team. Every prompt lands in Postgres in plain text, next to the name of the person who typed it.\n\n`az account get-access-token` as a token command. It worked, but it silently reused my Azure CLI session and never asked me to sign in. The built-in `gateway_oauth` flow is the one that prompts.`codex mcp list` shows `Not logged in` until you run `codex mcp login`.` http://127.0.0.1/callback` covers any port for the model sign-in. The MCP callback has an extra path segment and needs its own entry.`groups` claim for such users, and the policy answers 403. The fix is to emit only groups assigned to the application.`gpt-oss-20b` and `claude-haiku-4-5` next to `gpt-oss-120b`. All three sit behind the same policy, and `codex -m claude-haiku-4-5` uses the same sign-in.\nThe repo has this as a 10-step guide with every command, a troubleshooting table and a script for the Entra setup: [entra-id/README.md](https://github.com/sebbycorp/agentgateway-oss-k8s/blob/main/entra-id/README.md).\n\nRelated posts:", "url": "https://wpnews.pro/news/add-entra-id-sign-in-to-codex-cli-through-agentgateway-part-2", "canonical_source": "https://agentgateway.dev/blog/2026-11-19-codex-cli-entra-id-sign-in-agentgateway/", "published_at": "2026-11-19 00:00:00+00:00", "updated_at": "2026-11-19 14:15:19.196529+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "agent-protocols", "developer-tools"], "entities": ["Codex CLI", "agentgateway", "Microsoft Entra ID", "Amazon Bedrock", "Solo.io", "sebbycorp/agentgateway-oss-k8s"], "also_reported_by": [], "takeaway": "Set `groupMembershipClaims=SecurityGroup`, `requestedAccessTokenVersion: 2` and a public-client loopback redirect on the Entra app registration, or the gateway returns 403 for missing groups and 401 for the old v1 issuer.", "recommendation": {"advice": "Front Codex CLI with agentgateway and require an Entra ID token plus `codex` group membership; skipping the group claim yields 403 and skipping v2.0 tokens yields 401.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/add-entra-id-sign-in-to-codex-cli-through-agentgateway-part-2", "markdown": "https://wpnews.pro/news/add-entra-id-sign-in-to-codex-cli-through-agentgateway-part-2.md", "text": "https://wpnews.pro/news/add-entra-id-sign-in-to-codex-cli-through-agentgateway-part-2.txt", "jsonld": "https://wpnews.pro/news/add-entra-id-sign-in-to-codex-cli-through-agentgateway-part-2.jsonld"}}