Solving the Identity Termination Problem in MCP Gateway Architectures
From the publisher’s feed, collected in the ZeroLabs newsroom.
Enterprises deploying Model Context Protocol (MCP) gateways should adopt a dual OAuth boundary so that the calling user’s identity survives the gateway hop and authorizes every downstream system on the user’s behalf.The problemTrace the failure end to end. A user asks an MCP-fronted agent to open a ticket on behalf of a colleague. The gateway authenticates the user against the enterprise IdP, validates the bearer token, and forwards the call to the IT-service-management API. The API accepts the call and writes the ticket. Thirty days later, an auditor queries the ticket store. Every ticket created by the agent in the past month names the same actor: the gateway’s own application identity. The human users who actually triggered the actions appear nowhere in the audit trail.The failure repeats on every downstream system the gateway fronts. The HRIS attributes every PTO request to the gateway service account. The asset registry attributes every device transfer to it. The procurement workflow lists it as the approver of every requisition. Identity terminated at the gateway hop, and no instrument downstream of that hop can recover it.MCP gateways have become the default integration surface between LLM agents and enterprise systems of record, and most production deployments leave one question ambiguous: whose identity authorizes each downstream call [7]. Two anti-patterns dominate the field.In the terminated-identity anti-pattern, the gateway authenticates the caller, then opens downstream connections under a single service principal. Every action the gateway takes against the IT system, the HRIS, and the procurement workflow is attributable to the gateway’s service account, not to the human user who triggered it. Audit trails become unusable. Least-privilege collapses. A misbehaving prompt can authorize the gateway’s full blast radius against any backend it can reach.In the trust-the-client anti-pattern, the gateway accepts whatever bearer token the caller sends and forwards it unmodified to downstream APIs, with no validation of issuer, audience, or scope. Token theft anywhere on the agent path silently authorizes arbitrary downstream calls.Neither pattern is acceptable for enterprise agentic AI, particularly under the NIST AI Risk Management Framework Govern function [6], which requires that individual user accountability is preserved across automated actions on regulated systems.The claimEnterprises deploying MCP gateways should architect them with a dual OAuth boundary. The inbound boundary extracts and validates a delegated-access token (an OAuth 2.0 bearer token issued to the calling user against the gateway’s audience) [1] at the client edge. The outbound boundary performs an on-behalf-of exchange [2], or where the trust chain permits, a direct delegated forwarding, to produce a downstream-audience token that still carries the original user’s identity. Tool authorization decisions are made at the boundary against parsed token claims, not deep in tool implementations. Identity propagation becomes a property of the gateway, not of any one tool or backend service.The pattern: Delegated Boundary OAuth (DBO)The gateway carries two OAuth boundaries, not one. User identity is the contract that flows between them.Source: Image by the author.The first boundary is inbound. Bearer-token extraction, issuer-and-audience validation, and claims parsing happen at a single layer of the gateway: typically a request middleware or a FastMCP-style dependency injector that runs before any tool function executes. The inbound boundary is the place where the question “who is calling, and are they authorized for this tool?” gets answered. No tool implementation is permitted to bypass it. Scope-to-tool mapping is declarative: every exposed tool declares the OAuth scopes it requires, and the boundary refuses execution when the inbound token does not carry them. The refusal is a structured authorization-failure response, not a 5xx from a deeper-in-the-stack permission check that wasted compute getting there.The second boundary is outbound. The downstream API call is authenticated with a token that names the original user, never with the gateway’s own service identity. Two mechanisms achieve this. An on-behalf-of exchange (Microsoft Entra OBO, AWS Cognito identity-pool exchange, custom STS exchange) mints a new token whose audience is the downstream API and whose subject is still the human caller. Direct token forwarding, used only when the downstream service is inside an explicit trust agreement with the gateway, passes the inbound token through unchanged. The exchange is the security boundary that makes identity propagation provable rather than aspirational.Between the two boundaries, the gateway treats tokens as request-scoped state. No caching of user tokens across requests, no session-bound storage, no shared mutable state. Each MCP tool invocation re-extracts the token from the live request headers and discards it at the end of the request lifecycle. This aligns DBO with the Stateless HTTP Container Isolation (SHCI) discipline: the same statelessness that makes containers replaceable is what keeps user identity bound to a single request and only that request.ImplementationInbound boundary: delegated-token extractionThe inbound boundary is a thin middleware that runs before every tool function. In a Python MCP server using a FastMCP-style framework, the pattern is to depend on a CurrentHeaders injection and extract the bearer token with a single utility:from typing import Optionaldef extract_bearer_token(headers: dict) -> str: auth = headers.get("authorization") or headers.get("Authorization") if not auth or not auth.startswith("Bearer "): raise AuthError("missing or malformed bearer token") return auth[len("Bearer "):]The token is then validated against the gateway’s expected issuer and audience using the IdP’s signing keys (JWKS):from jose import jwtdef validate_inbound_token(token: str, jwks: dict, audience: str, issuer: str) -> dict: claims = jwt.decode( token, jwks, audience=audience, issuer=issuer, options={"require_exp": True, "require_iat": True}, ) return claims # sub, scp/scope, exp, etc.Validation must occur in-process. Outsourcing JWT validation to a downstream proxy works in narrow trust topologies but eliminates the gateway’s ability to enforce scope-to-tool mapping before tool side-effects execute.Outbound boundary: on-behalf-of token exchangeThe outbound boundary exchanges the inbound user token for a downstream-audience token. The exchange is what distinguishes DBO from naive forwarding: the downstream API never sees the inbound token directly. Instead, the gateway calls the IdP’s token endpoint with a urn:ietf:params:oauth:grant-type:jwt-bearer (Entra) [3] or assume-role-with-web-identity (AWS) [4] request, passing the inbound token as the subject assertion. The IdP returns a new token whose audience is the downstream API and whose sub claim is still the original user.def exchange_obo(inbound_token: str, downstream_audience: str) -> str: response = requests.post( f"{IDP_TOKEN_ENDPOINT}", data={ "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "client_id": GATEWAY_CLIENT_ID, "client_secret": GATEWAY_CLIENT_SECRET, "assertion": inbound_token, "scope": f"{downstream_audience}/.default", "requested_token_use": "on_behalf_of", }, timeout=5, ) response.raise_for_status() return response.json()["access_token"]The exchanged token is attached to the outbound HTTP call:def call_downstream(downstream_token: str, path: str) -> dict: return requests.get( f"{DOWNSTREAM_BASE_URL}{path}", headers={"Authorization": f"Bearer {downstream_token}"}, timeout=10, ).json()Scope mapping and identity propagationTool functions declare required scopes on registration; the boundary enforces them before invoking the tool body:@tool(required_scopes=["ticketing.write"])def open_ticket(headers: CurrentHeaders, summary: str, body: str) -> dict: token = extract_bearer_token(headers) claims = validate_inbound_token(token, jwks, audience=GATEWAY_AUD, issuer=ISSUER) enforce_scopes(claims, required=["ticketing.write"]) # central, not tool-local downstream_token = exchange_obo(token, downstream_audience=TICKETING_AUD) return call_downstream(downstream_token, path="/tickets")Scope mapping is declarative and discoverable. A reviewer auditing the gateway can list every tool with its required scopes by reading the tool registry, without reading any tool body.The inbound boundary is identical across suppliers; only the outbound exchange wiring differs. The two implementations below share one DBO shape.Source: Image by the author.AWS implementation (Amazon API Gateway + AWS Lambda + Amazon Cognito)On AWS, the inbound boundary is implemented as an Amazon API Gateway custom Lambda authorizer that validates the inbound token against an Amazon Cognito user pool [5] and returns a policy document plus a context map with the parsed claims. The MCP-server Lambda receives the claims via event.requestContext.authorizer rather than re-validating. The outbound boundary uses sts:AssumeRoleWithWebIdentity with the inbound token (or a Cognito-issued identity-pool token) to obtain short-lived AWS credentials whose principal is the original user's federated identity. Downstream Amazon API Gateway endpoints, or non-AWS APIs that accept Cognito-issued JWTs, receive a token whose sub claim is the user.A minimal-viable Cognito + STS exchange in the gateway Lambda:import boto3def aws_obo(inbound_token: str, role_arn: str) -> dict: sts = boto3.client("sts") creds = sts.assume_role_with_web_identity( RoleArn=role_arn, RoleSessionName="mcp-gateway-obo", WebIdentityToken=inbound_token, DurationSeconds=900, ) return creds["Credentials"]The trust policy on the assumed role pins the Cognito user pool as the federated principal and conditions on the inbound token’s aud claim, so the role can be assumed only with a token issued for this gateway.Azure implementation (Microsoft Entra ID on-behalf-of flow)On Azure, the inbound boundary validates the incoming token against the gateway’s Entra app registration (audience = the gateway’s Application ID URI). The outbound boundary performs an Entra OBO exchange against the downstream API’s app registration:import msaldef entra_obo(inbound_token: str, downstream_scope: str) -> str: app = msal.ConfidentialClientApplication( client_id=GATEWAY_APP_ID, client_credential=GATEWAY_CLIENT_SECRET, authority=f"https://login.microsoftonline.com/{TENANT_ID}", ) result = app.acquire_token_on_behalf_of( user_assertion=inbound_token, scopes=[downstream_scope], ) if "access_token" not in result: raise AuthError(result.get("error_description", "obo exchange failed")) return result["access_token"]The downstream API is configured to accept tokens whose audience is its own Entra app registration. Its authorization logic reads oid (object id) or upn (user principal name) claims to attribute the call to the original user. Identical pattern shape; different IdP wiring.Integration with EGAL, SHCI, and URESDBO is the auth-discipline counterpart to three companion patterns in this series. The user identity DBO extracts at the inbound boundary is the identity the Evidence-Logged Agent Loop (EGAL) [8] records on every tool invocation: DBO produces the identity field that EGAL is required to log. The request-scoped token handling DBO prescribes is the same statelessness the Stateless HTTP Container Isolation (SHCI) [9] pattern requires of MCP containers on serverless runtimes; DBO’s token discipline is what makes SHCI’s container-isolation discipline tractable. And the user identity DBO propagates becomes a first-class field in the Unified RAG Evaluation Schema (URES) [10] record (the invokingUser field alongside judgeModel and systemUnderTest), tying evaluations back to the individuals whose behavior the system is actually responding to. Together, DBO, SHCI, EGAL, and URES constitute a coherent architectural stack for production MCP agents. DBO supplies the auth discipline. SHCI keeps the runtime honest. EGAL captures the evidence. URES measures what all three produce.When this pattern fits / when it doesn’tFits when:The MCP gateway fronts systems where individual user identity matters for authorization, audit, or compliance: IT-service-management, HR, finance, regulated workflows.The enterprise IdP supports a standard on-behalf-of exchange (Entra OBO, Cognito + STS web identity, Auth0/Okta token exchange).Downstream APIs are under the same trust boundary as the gateway and can be configured to accept user-audience tokens.The deployment is subject to NIST AI RMF, SOX, HIPAA, or comparable governance requiring user-level accountability of automated actions.Doesn’t fit when:Every downstream call is provably non-user-specific (purely read-only reference data, no user-attributable side effects).A trusted downstream proxy already enforces full DBO semantics on the gateway’s behalf and the gateway’s added value would be duplicative. In that case the gateway implements only the inbound boundary and a delegated-trust variant of the outbound (direct forwarding under the explicit trust contract with the proxy), accepting that the proxy is the security boundary.The downstream API does not accept user-audience tokens and refactoring it is out of scope. DBO must be deferred until that constraint is removed. Substituting a service principal “for now” is a deliberate decision with documented risk acceptance, not a default.Operational considerations:Latency. OBO exchanges add a token-endpoint round-trip per downstream call. Cache exchanged tokens for the lifetime of the inbound token’s remaining validity, keyed by (sub, downstream_audience). Never cache across users.IdP throttling. Token-endpoint quotas are non-trivial. Provision headroom and instrument exchange-failure rates.Refresh. Long-running agent sessions outlive single token lifetimes. Plan for refresh-token rotation, or accept that an agent run-loop terminates at token expiry, which is often the correct security posture.Service-account fallback. Reserve a service-account exchange path for genuinely user-less operations (health checks, scheduled background sync). Make this path explicit, narrowly scoped, and logged.Where this pattern is incompleteDBO assumes the enterprise IdP supports a standard on-behalf-of exchange. Many older IdPs do not. For those environments the outbound boundary degrades to direct token forwarding under an explicit trust contract with each downstream service, which is acceptable for backends inside the gateway’s trust boundary but insufficient when the downstream service is operated by a separate team or third-party vendor. The right migration path is the IdP upgrade, not a permanent fallback to forwarding.DBO also assumes downstream services accept user-audience tokens. Many enterprise systems were built before delegated authorization was common and authenticate only against service principals. In those cases DBO must be deferred until the downstream service is upgraded or until an intermediate identity-aware proxy is introduced. Operating DBO partially (some downstream calls user-attributed, others service-attributed) is the default during the migration period, but it should be tracked as technical debt with a closure date, not normalized as the steady state.Finally, DBO does not solve agent-as-actor accountability. The pattern preserves the human user’s identity across the gateway hop, which is the right primary control. But an LLM agent can still be prompted to perform actions the user did not literally request. DBO ensures attribution; it does not ensure intent. Compensating controls (human-in-the-loop confirmation for high-impact actions, scope minimization at the inbound boundary, EGAL-compliant per-call evidence logging) carry the weight that DBO cannot.Adoption checklistPublish the inbound-boundary contract (issuer, audience, supported scopes) as a versioned interface document. Treat it as a public API of the gateway.Implement scope-to-tool mapping as a declarative tool-registration field, not as imperative checks scattered through tool bodies.Wire an on-behalf-of exchange against the enterprise IdP for every downstream backend. Default to OBO; reserve direct forwarding for backends that are inside the gateway’s explicit trust boundary.Cache exchanged tokens within the inbound-token lifetime, keyed by user-subject + downstream audience. Never share tokens across users.Log the inbound-token sub and the outbound-token sub on every tool invocation (EGAL-compliant) so identity propagation is auditable end-to-end.Reserve a single, narrowly scoped service-account path for user-less operations and treat its use as an exception requiring approval, not a default.Re-evaluate downstream APIs that do not accept user-audience tokens as architectural debt; track them and retire the constraint over time.As US enterprises and federal programs adopt the NIST AI Risk Management Framework [6], the Govern function requires that individual user accountability is preserved across automated actions on regulated systems. Service-principal termination at the gateway directly violates that requirement, exposing enterprises to audit deficiencies in SOX, HIPAA, and FedRAMP environments where every automated state change must trace to a named human principal.References[1] Internet Engineering Task Force, “RFC 6749: The OAuth 2.0 Authorization Framework,” IETF, 2012.[2] Internet Engineering Task Force, “RFC 8693: OAuth 2.0 Token Exchange,” IETF, 2020.[3] Microsoft, “Microsoft identity platform and OAuth 2.0 On-Behalf-Of flow,” Microsoft Learn, 2026.[4] Amazon Web Services, “AssumeRoleWithWebIdentity — AWS Security Token Service API Reference,” AWS Documentation, 2026.[5] Amazon Web Services, “Amazon Cognito identity pools (federated identities),” AWS Documentation, 2026.[6] National Institute of Standards and Technology, “Artificial Intelligence Risk Management Framework (AI RMF 1.0),” NIST, 2023.[7] Model Context Protocol, “Specification: Authorization,” 2025.[8] N. Selvaraj, “The Evidence-Logged Agent Loop: Structured Tool-Call Logging for Agentic Systems,” Medium, 2026.[9] N. Selvaraj, “Stateless HTTP Container Isolation: Why MCP Servers on Serverless Runtimes Must Disable Session Routing,” Medium, 2026.[10] N. Selvaraj, “Unified RAG Evaluation Schema: Cross-Supplier Quality Measurement for Amazon Bedrock and Agentic Workloads,” Medium, 2026.Solving the Identity Termination Problem in MCP Gateway Architectures was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.