NEWn1n v2.0.1 is live! Enterprise Unified LLM API Gateway with 500+ AI Models, up to 90% off, Try now

ServiceNow Token Exchange with Bedrock AgentCore Gateway

Authors
  • avatar
    Name
    Nino
    Occupation
    Senior Tech Editor

Building enterprise-grade AI agents requires more than just connecting a foundational model like Claude 3.5 Sonnet to an LLM API. It demands strict adherence to security protocols, such as preserving the end-user identity when downstream systems like ServiceNow are invoked. Traditionally, developers had to write custom interceptor Lambda functions to manage the OAuth 2.0 on-behalf-of (OBO) token exchange. However, with Amazon Bedrock AgentCore Gateway, this capability is now natively integrated, streamlining the entire architecture for developers utilizing a reliable LLM API aggregator like n1n.ai.

In this deep dive, we will explore the architectural patterns, step-by-step configuration workflows, and code implementations required to orchestrate a seamless user-identity-preserving workflow between your LLM agent and the ServiceNow REST API using Microsoft Entra ID (formerly Azure AD).

Understanding the On-Behalf-Of (OBO) Flow in AI Gateways

When a user interacts with an AI agent—whether through a custom chat interface or an enterprise workspace—the request carries the user's authentication token, typically a JSON Web Token (JWT) issued by an Identity Provider (IdP) like Microsoft Entra ID. When the agent decides to invoke an external tool, such as creating an incident in ServiceNow, the API call must execute with the permissions of that specific user, rather than a generic service account.

Historically, achieving this meant:

  1. Capturing the incoming user token at the application layer.
  2. Passing the token through custom execution context.
  3. Deploying an AWS Lambda function to intercept the request, call the Microsoft identity platform's /token endpoint using the urn:ietf:params:oauth:grant-type:jwt-bearer grant type, and exchange the user token for a downstream access token.
  4. Injecting the new token into the authorization header for ServiceNow.

This architecture introduced latency, maintenance overhead, and security vulnerabilities. The introduction of Bedrock AgentCore Gateway changes the game by handling the OAuth 2.0 token exchange natively at the gateway level.

FeatureTraditional Lambda InterceptorBedrock AgentCore Gateway (Native OBO)
Latency OverheadHigh (> 150ms per tool call)Low (Handled natively < 20ms)
Maintenance CostHigh (Custom code, secret rotation)Low (Managed service configuration)
Security RiskGreater exposure of client secretsSecure, centralized credential management
Integration ComplexityRequires custom middlewareNative tool definition mapping

Step-by-Step Configuration Guide

To configure the AgentCore Gateway for native OBO token exchange with Microsoft Entra ID and ServiceNow, follow this structured implementation path. If you are testing your agent loops locally using tools provided by platforms like n1n.ai, ensure your environment variables match the production configurations.

Step 1: Register Applications in Microsoft Entra ID

You need to establish trust relationships within your enterprise directory:

  1. Agent Application (Client): Register an application representing your AI agent. Grant it API permissions to request tokens on behalf of users.
  2. ServiceNow Target API: Expose an application scope on your ServiceNow integration or register the ServiceNow enterprise application within Entra ID to accept tokens issued by your tenant.

Step 2: Configure Bedrock AgentCore Gateway

Navigate to the Amazon Bedrock console, select AgentCore Gateways, and create a new gateway instance. You will configure the upstream authentication and the downstream credential provider.

{
  &quot;gatewayName&quot;: &quot;enterprise-servicenow-gateway&quot;,
  &quot;authentication&quot;: {
    &quot;type&quot;: &quot;OAuth2&quot;,
    &quot;identityProviderConfig&quot;: {
      &quot;issuer&quot;: &quot;https://login.microsoftonline.com/&lt;tenant-id&gt;/v2.0&quot;,
      &quot;clientId&quot;: &quot;&lt;agent-client-id&gt;&quot;
    }
  },
  &quot;tokenExchange&quot;: {
    &quot;grantType&quot;: &quot;urn:ietf:params:oauth:grant-type:jwt-bearer&quot;,
    &quot;scope&quot;: &quot;https://service-now.api.domain/.default&quot;,
    &quot;clientSecretArn&quot;: &quot;arn:aws:secretsmanager:us-east-1:123456789012:secret:entra-client-secret&quot;
  }
}

Step 3: Define the ServiceNow Tool Schema

Next, define the OpenAPI schema for the ServiceNow REST API endpoint that your agent will access. The gateway utilizes this schema to map agent intent parameters directly to HTTP requests.

{
  &quot;openapi&quot;: &quot;3.0.0&quot;,
  &quot;info&quot;: {
    &quot;title&quot;: &quot;ServiceNow Incident API&quot;,
    &quot;version&quot;: &quot;1.0.0&quot;
  },
  &quot;paths&quot;: {
    &quot;/api/now/table/incident&quot;: {
      &quot;post&quot;: {
        &quot;summary&quot;: &quot;Create Incident&quot;,
        &quot;operationId&quot;: &quot;createIncident&quot;,
        &quot;parameters&quot;: [
          {
            &quot;name&quot;: &quot;short_description&quot;,
            &quot;in&quot;: &quot;query&quot;,
            &quot;required&quot;: true,
            &quot;schema&quot;: {
              &quot;type&quot;: &quot;string&quot;
            }
          }
        ],
        &quot;responses&quot;: {
          &quot;201&quot;: {
            &quot;description&quot;: &quot;Incident created successfully&quot;
          }
        }
      }
    }
  }
}

Integrating with Your Application Code

When invoking the agent from your backend application, pass the user's incoming JWT directly in the authorization header. The Bedrock runtime will capture this token and execute the OBO exchange automatically before hitting ServiceNow.

import boto3
import requests

# Initialize bedrock client
client = boto3.client(&quot;bedrock-agent-runtime&quot;, region_name=&quot;us-east-1&quot;)

def invoke_agent_with_user_token(user_jwt, prompt_text):
    response = client.invoke_agent(
        agentId=&quot;YOUR_AGENT_ID&quot;,
        agentAliasId=&quot;YOUR_ALIAS_ID&quot;,
        sessionId=&quot;session-12345&quot;,
        inputText=prompt_text,
        sessionState={
            &quot;invocationType&quot;: &quot;USER_CONTEXT&quot;,
            &quot;authToken&quot;: user_jwt
        }
    )
    return response

Pro Tips for Enterprise Deployment

  1. Token Caching: Configure token caching windows appropriately in your IdP to minimize latency spikes during high-concurrency agent interactions.
  2. Scope Minimization: Ensure the Entra ID scopes requested by the AgentCore Gateway strictly align with the principle of least privilege required for ServiceNow operations.
  3. Unified Aggregation: For developers testing multi-model setups alongside Bedrock, integrating your development pipelines with n1n.ai ensures consistent API routing, rate limiting, and cost monitoring across different model providers.

Get a free API key at n1n.ai