{"slug": "building-a-secure-auth-code-flow-setup-using-agentcore-gateway-with-mcp-clients", "title": "Building a secure auth code flow setup using AgentCore Gateway with MCP clients", "summary": "Amazon Bedrock AgentCore Gateway now supports OAuth authorization code flow as an inbound authentication mechanism for MCP servers, enabling secure, identity-verified access between agentic coding assistants and enterprise tools. The setup requires an identity provider such as Amazon Cognito, Okta, or Microsoft Entra ID to issue user identity tokens that the Gateway validates before proxying requests to MCP servers. This implementation allows organizations to ensure that only authorized users and agents can access backend tools and services through AI assistants like Kiro IDE.", "body_md": "[Artificial Intelligence](https://aws.amazon.com/blogs/machine-learning/)\n\n# Building a secure auth code flow setup using AgentCore Gateway with MCP clients\n\nIn modern development workflows, developers increasingly rely on agentic coding assistants such as [Kiro Integrated Development Environment (IDE)](https://kiro.dev/) to interact with remote tools and services. However, organizations require robust authentication mechanisms to provide secure, identity-verified access between these agentic coding assistants and enterprise [Model Context Protocol (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro) servers.\n\n[Amazon Bedrock AgentCore](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html) is a fully managed service that helps you deploy, manage, and scale AI agents in production. One of its key components, the [AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html), provides a centralized entry point for routing and securing agent-to-tool communications. When an AI assistant makes a request to an MCP server through the Gateway, that request must be verified before it’s processed. This is known as *inbound authentication*. Only authorized users and agents can access the tools and services exposed by the MCP server. Organizations typically manage user identities through an identity provider (IdP), such as Okta, Microsoft Entra ID, or [Amazon Cognito](https://aws.amazon.com/cognito/), which authenticates users and issues security tokens that verify who they are.\n\nThis post demonstrates how to implement Open Authorization (OAuth) Code flow as an inbound authorization mechanism for MCP servers hosted on [Amazon Bedrock AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html). By the end of this guide, you will have a production-ready setup where each AI assistant request is authenticated with a valid user identity token issued from your organization’s identity provider.\n\n#### What you will learn\n\n- How auth code flow works with AgentCore Gateway as an MCP resource server.\n- Step-by-step configuration of your organization’s identity provider.\n- AgentCore Gateway inbound authentication setup.\n- Integration with Kiro IDE clients.\n\n## Solution overview\n\nIn an inbound authorization code flow OAuth setup, the AgentCore Gateway acts as an *MCP resource server* that requires a valid identity token before allowing AI clients to access any tools.\n\nThe following diagram shows the end-to-end architecture for the authorization code flow with AgentCore Gateway, including the identity provider, AI client, and MCP server interactions.\n\n*Figure 1: Authorization code flow architecture diagram.*\n\n### Key components\n\nThe solution involves the following components working together to complete the authentication flow:\n\n**Identity provider (IdP):** Manages user authentication and issues tokens. The preceding diagram references Amazon Cognito, but it can be your organization’s IdP.**User:** The end user who authenticates with the IdP and whose identity is verified for each request.**Amazon Bedrock AgentCore Gateway:** Acts as the OAuth resource server, validating tokens and proxying requests to MCP servers.**Agentic coding assistant:** Kiro IDE, which acts as the OAuth client and manages the authentication flow.**MCP server:** Your backend tools and services that the AI assistant needs to access.**MCP OAuth proxy (optional):** Helps bridge the gap of spec standardization between agentic coding assistants, IdPs, and MCP servers. An MCP OAuth proxy brings standardization that supports the authorization code flow.\n\n### The inbound authorization code flow\n\nThis flow makes sure that every request that the AI assistant sends to the MCP server is authenticated with a valid identity token belonging to the user.\n\n**MCP client connection**– The agentic coding assistant (for example, Kiro IDE) initiates a connection to the AgentCore Gateway’s MCP endpoint.** Authentication challenge**– The Gateway detects that the request lacks a valid token and responds with an HTTP 401, including a`www-authenticate`\n\nheader pointing to the Gateway’s OAuth Protected Resource Metadata endpoint (`.well-known/oauth-protected-resource`\n\n). This follows the MCP specification’s[Protected Resource Metadata (PRM) pattern](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).**Discovery**– The MCP client fetches the Protected Resource Metadata from the Gateway, which returns the IdP’s authorization server discovery URL (for example,`https://{yourIdPDomain}/oauth2/default/.well-known/openid-configuration`\n\n).**User redirection**– The MCP client opens the user’s system browser and redirects to the IdP’s authorization endpoint with a PKCE challenge, requesting the configured scopes (for example,`openid profile email offline_access`\n\n).**User authentication and consent**– The user enters their credentials on the IdP login page. The IdP verifies the user’s identity and prompts for consent to authorize the application.**Authorization code grant**– After approval, the IdP redirects the user’s browser to the client’s local callback URL (managed by the client’s local listener) with an authorization code.**Token exchange request**– The MCP client sends the authorization code along with the PKCE code verifier to the IdP’s token endpoint.** Token issuance**– The IdP validates the authorization code and PKCE verifier, then returns an access token (and optionally a refresh token) to the MCP client.**Authenticated MCP request and validation**– The MCP client includes the access token in the`Authorization`\n\nheader for all subsequent requests. The Gateway validates the token’s signature, expiration, issuer, and audience or custom claims, then proxies the request to the target MCP server for execution.\n\n*Figure 2: Authorization code flow request sequence.*\n\n### Configuration overview\n\nThe following table summarizes the required configuration for each component in the authorization code flow setup. Detailed step-by-step instructions follow in the Technical implementation section.\n\nComponent |\nRequired configuration |\n|\n| 1 | Identity provider |\nCreate an OpenID Connect (OIDC) web application with Authorization Code and Refresh Token grants enabled. |\n| 2 | AgentCore Gateway |\nSet inbound authorization to JWT. Configure the discovery URL to your IdP’s issuer (for example, `https://{yourIdPDomain}/oauth2/default/.well-known/openid-configuration` ). |\n| 3 | Kiro IDE |\nAdd the Gateway URL in Settings > Connectors (or through the CLI). The client automatically triggers the OAuth flow if the Gateway returns a 401 Unauthorized with the correct auth headers. |\n\n## Technical implementation\n\nWith the architecture and flow established, configure each component. This section provides step-by-step instructions for the three components referenced in the configuration overview table:\n\n**Identity provider**: Register an OIDC application and configure grant types, redirect URIs, and token settings.** AgentCore Gateway**: Enable JWT-based inbound authorization and point it to your IdP’s discovery endpoint.** MCP client (Kiro IDE)**: Connect the client to the Gateway URL and verify the end-to-end OAuth flow.\n\n### Prerequisites\n\nYou must have the following prerequisites in place to follow along.\n\n- An AWS account with\n[AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-building.html)deployed. - An identity provider (IdP) with permissions to configure an app (for example, Amazon Cognito, Okta, Auth0, or other enterprise identity providers).\n- MCP OAuth proxy.\n- Kiro IDE installed locally.\n- Basic understanding of\n[OAuth 2.0](https://oauth.net/2/)flows.\n\n### Step 1: Configure the organization’s identity provider\n\nIn this step, you register an OIDC application with your organization’s identity provider and configure it to support the authorization code flow with PKCE.\n\n#### 1.1 Create an OIDC application\n\nSign in to your IdP admin console and create a new OIDC/OAuth 2.0 application integration:\n\n**Sign-in method:** OIDC.**Application type:** Web application.**Name:** AgentCore Gateway client (or your preferred name).\n\n#### 1.2 Configure grant types\n\nEnable the following grant types:\n\n- Authorization Code.\n- Refresh Token.\n\n#### 1.3 Set redirect URIs\n\nAdd the callback URL that your AI client will use:\n\n```\nhttp://localhost:PORT/callback\n```\n\nReplace `PORT`\n\nwith the port that your [client uses](https://kiro.dev/docs/enterprise/identity-provider/okta/#create-new-app-integration).\n\n#### 1.4 Configure token settings\n\nIn your IdP application settings, do the following.\n\n**Token lifetimes:**\n\n**Access token lifetime:** 1 hour (recommended).**Refresh token lifetime:** 90 days (adjust based on your security requirements).**ID token lifetime:** 1 hour.\n\n#### 1.5 Note your configuration\n\nSave the following values. You will need them for Gateway configuration:\n\n**Client ID:** Found in the application’s General tab (needed for Kiro IDE client configuration).**Issuer URL:** Your IdP’s issuer URL (for example,`https://{yourIdPDomain}/oauth2/default`\n\n).**Discovery URL:** Your IdP’s OpenID Connect discovery endpoint (for example,`https://{yourIdPDomain}/oauth2/default/.well-known/openid-configuration`\n\n).\n\nFor this configuration:\n\n**No client secret required**– This flow uses PKCE (Proof Key for Code Exchange), which is designed for public clients like desktop applications. The client secret is not needed or used by Kiro IDE.**No IdP endpoints in client config**– Kiro IDE discovers the OAuth endpoints automatically from the Gateway, which returns the discovery URL. You don’t configure IdP URLs directly in the client.\n\n### Step 2: Configure AgentCore Gateway\n\nWith your identity provider configured, the next step is to connect AgentCore Gateway to your IdP so it can validate incoming tokens.\n\n#### 2.1 Set inbound authorization mode\n\nConfigure your Gateway to use JWT-based authentication with your IdP’s discovery endpoint:\n\n#### 2.2 Custom claim validation\n\nAgentCore Gateway validates JWT tokens based on standard OAuth 2.0 claims and supports custom claim validation to accommodate different IdP implementations. The Gateway expects tokens to contain:\n\n**Standard claims:**`iss`\n\n(issuer),`aud`\n\n(audience),`exp`\n\n(expiration),`iat`\n\n(issued at),`client_id`\n\n(client identity), and`scopes`\n\n(allowed scopes).**Client identification:** The Gateway can validate client identity through various claims depending on your IdP.\n\nOther IdPs might use different claim names for client identification, scopes, and so on (for example, `cid`\n\n, `azp`\n\n, `scp`\n\n). You can configure custom claim validation in your Gateway to match your IdP’s token structure:\n\n**Custom claim:**`<claim-name> EQUALS <expected-value>`\n\n(see[AgentCore Gateway: Set up a JWT](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-inbound-auth.html)).- Example:\n`cid EQUALS 0oaz7147z771FZmdQ697`\n\n(for IdPs that use`cid`\n\n, like Okta). - This validates that the token was issued for your specific application.\n\n**Note:** The Gateway’s **Allowed audience** field can be kept empty when using custom claim validation. The custom claim check provides the necessary client identity verification.\n\n#### 2.3 Understand Gateway token validation\n\nNow that the Gateway is configured with your IdP’s discovery URL and claim rules, look at how it validates incoming tokens at runtime.\n\nAgentCore Gateway is designed to be agnostic to how the OAuth token was obtained by the user. The Gateway doesn’t distinguish between tokens acquired through the following:\n\n**Client credentials flow**, where the application authenticates directly.** Authorization code flow**, where the user explicitly authenticates and grants consent.\n\nThe Gateway only requires that the OAuth token presented in the request is valid based on the parameters configured during Gateway setup:\n\n**Token signature:** Verified against the public keys from the IdP’s discovery URL.**Token expiration:** Validates the token hasn’t expired.**Issuer (** Matches the expected IdP issuer.`iss`\n\nclaim):**Audience or custom claims:** Validates the token was issued for this specific Gateway or application.**Standard OAuth claims:** Checks required claims like`iat`\n\n,`exp`\n\n, and so on.\n\nWhether users obtain tokens through a client credentials flow, authorization code flow, or other OAuth grant type, the Gateway treats all tokens equally. As long as the token passes the validation checks configured in your Gateway setup, the request is authorized. With this flexibility, you can choose the authentication flow that fits your use case while maintaining consistent security at the Gateway level.\n\n#### 2.4 Verify Gateway configuration\n\nTest that your Gateway endpoint is accessible and requires authentication:\n\nThe following response confirms that authentication is properly configured (a 401 response to unauthenticated MCP requests):\n\n```\n# Expected response showing authentication is required:\nHTTP/2 401\nwww-authenticate: Bearer resource_metadata=\"https://<your-gateway-url>/.well-known/oauth-protected-resource\"\n{\"jsonrpc\":\"2.0\",\"id\":0,\"error\":{\"code\":-32001,\"message\":\"Missing Bearer token\"}}\n```\n\n### Step 3: MCP OAuth proxy\n\nFor the purpose of this post, use `mcp-remote`\n\nto standardize the MCP client interface and complete the authorization code flow.\n\n#### 3.1 Install the mcp-remote package\n\nUse [mcp-remote](https://www.npmjs.com/package/mcp-remote) to bridge Kiro IDE’s MCP client with the Gateway’s OAuth-protected endpoint.\n\n**Note:** `mcp-remote`\n\nis a working proof-of-concept and should be considered experimental.\n\n### Step 4: Configure the AI client (Kiro IDE)\n\nWith the Gateway and MCP OAuth proxy configured, the final configuration step is connecting your AI client to the Gateway endpoint. Kiro IDE handles the OAuth flow automatically. When it receives a 401 challenge from the Gateway, it initiates the authorization code flow with your IdP.\n\n#### 4.1 Configure Kiro IDE\n\nAdd the Gateway to your MCP configuration file at `~/.kiro/settings/mcp.json`\n\n:\n\n**Configuration parameters:**\n\n`command`\n\n: Use`mcp-remote`\n\nto connect to remote MCP servers ([mcp-remote](https://www.npmjs.com/package/mcp-remote)).- First arg: Your Gateway URL with the\n`/mcp`\n\npath. - Second arg: Local port for the OAuth callback (for example,\n`3334`\n\n). `--static-oauth-client-info`\n\n: JSON string containing:`client_id`\n\n: Your IdP application client ID.`redirect_uris`\n\n: Must match the port specified in the second arg.`scope`\n\n: Include`openid profile email offline_access`\n\nfor basic auth.\n\n#### 4.2 Test the authentication flow\n\nAfter adding the Gateway connection, verify that the authentication flow completes successfully:\n\n- Restart your AI client.\n- Attempt to use a tool from the Gateway.\n- You’re redirected to your browser for IdP login.\n- After successful authentication, the tool runs.\n\n### Step 5: Verify the end-to-end flow\n\nAfter all components are configured and the initial authentication succeeds, verify that the full flow works end-to-end, from the AI client sending a tool request, through token validation at the Gateway, to receiving a response from the MCP server.\n\n#### 5.1 Check token validation\n\nMonitor your Gateway logs to confirm token validation:\n\n```\n# Example log entry showing successful validation\n[INFO] Token validated successfully for user: user@example.com\n[INFO] Executing tool: list_files\n```\n\nFor a step-by-step walkthrough using Okta as the IdP, see this [GitHub repo](https://github.com/awslabs/agentcore-samples/tree/main/06-workshops/02-AgentCore-gateway/17-inbound-auth-code-flow-okta).\n\n## Clean up\n\nIf you followed along with this post and want to undo the resources you created, complete the following steps. They’re presented in reverse order of creation so that dependent resources are removed before the components they rely on.\n\n### Revoke OAuth tokens\n\nBefore removing any configuration, revoke any active tokens issued during testing. Consult your IdP’s documentation for the exact revocation endpoint URL and supported parameters.\n\nKey considerations that vary by IdP:\n\n**Revocation endpoint URL:** Check your IdP’s OpenID Connect discovery document (the`revocation_endpoint`\n\nfield).**Token types accepted:** Some IdPs only accept refresh tokens. Others accept both access and refresh tokens.**Client authentication:** Public clients typically pass`client_id`\n\nin the body. Confidential clients might require a Basic Authorization header with encoded credentials.**Cascade behavior:** Revoking a refresh token usually invalidates its associated access tokens, but confirm with your IdP.\n\nYou can also clear locally cached tokens by removing the `mcp-remote`\n\nauth cache. On macOS or Linux:\n\n### Remove the AI client configuration (Kiro IDE)\n\nRemove the Gateway entry from your Kiro IDE MCP configuration at `~/.kiro/settings/mcp.json`\n\n. Delete the `gateway-tools`\n\nserver block you added in Step 4.\n\n### Remove the MCP OAuth proxy\n\nUninstall the `mcp-remote`\n\npackage you installed in Step 3:\n\n### Delete the AgentCore Gateway configuration\n\nRemove the inbound authentication configuration you set up in Step 2, or delete the Gateway entirely if you created it solely for this walkthrough:\n\n**Option A: Remove inbound auth (keep the Gateway)**\n\n**Option B: Delete the Gateway**\n\n### Remove the organization’s identity provider configuration\n\nDelete the OIDC application integration you created in Step 1:\n\n- Sign in to your IdP admin console.\n- Navigate to\n**Applications**>** Applications**. - Select the application you created (for example, “AgentCore Gateway client”).\n- Deactivate the application first (if required by your IdP), then delete it.\n\nThis revokes all client credentials and prevents any future token issuance for this application.\n\n## Conclusion\n\nIn this post, you learned how to implement secure, identity-verified access to MCP servers hosted on Amazon Bedrock AgentCore Gateway using inbound authorization code flow. With this setup, every AI assistant request is authenticated with a valid user token from your organization’s identity provider.\n\n#### Key takeaways\n\n- Authorization code flow provides strong authentication by requiring user consent and identity verification.\n- AgentCore Gateway acts as an OAuth resource server, validating tokens before allowing requests to invoke targets.\n- The flow is transparent to end users. They authenticate once, and tokens are automatically refreshed.\n- This architecture scales to support multiple AI clients and identity providers.\n\n#### Additional resources\n\n[AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html).[OAuth 2.0 authorization code flow](https://oauth.net/2/grant-types/authorization-code/).[OpenID Connect specification](https://openid.net/specs/openid-connect-core-1_0.html).[MCP specification](https://modelcontextprotocol.io/specification/2025-11-25).", "url": "https://wpnews.pro/news/building-a-secure-auth-code-flow-setup-using-agentcore-gateway-with-mcp-clients", "canonical_source": "https://aws.amazon.com/blogs/machine-learning/building-a-secure-auth-code-flow-setup-using-agentcore-gateway-with-mcp-clients/", "published_at": "2026-06-02 03:23:35+00:00", "updated_at": "2026-06-02 20:26:25.855740+00:00", "lang": "en", "topics": ["artificial-intelligence", "ai-agents", "ai-tools", "ai-infrastructure", "ai-products"], "entities": ["Amazon Bedrock AgentCore", "AgentCore Gateway", "Kiro IDE", "Model Context Protocol", "Okta", "Microsoft Entra ID", "Amazon Cognito"], "alternates": {"html": "https://wpnews.pro/news/building-a-secure-auth-code-flow-setup-using-agentcore-gateway-with-mcp-clients", "markdown": "https://wpnews.pro/news/building-a-secure-auth-code-flow-setup-using-agentcore-gateway-with-mcp-clients.md", "text": "https://wpnews.pro/news/building-a-secure-auth-code-flow-setup-using-agentcore-gateway-with-mcp-clients.txt", "jsonld": "https://wpnews.pro/news/building-a-secure-auth-code-flow-setup-using-agentcore-gateway-with-mcp-clients.jsonld"}}