In Governing a LangChain agent on AWS with Microsoft Entra Agent ID and Agent 365, without a single secret the agent ran on Amazon ECS with two helpers next to it: a token helper that kept an AWS-signed token in a shared file, and the Microsoft Entra auth sidecar that turned that token into Entra tokens for the agent.

That works when you control the task. Amazon Bedrock AgentCore Runtime runs one container per agent. There is no second container to put the sidecar in, no shared volume, no start-up ordering. So the question becomes: can the agent do the sidecar’s job itself, and still have its own Entra identity, act on behalf of a user, act as itself under Conditional Access for agents, and send its telemetry to Agent 365?

It can. This article shows how, in two languages:

  • .NET, with Microsoft.Identity.Web and its agent identities package, plus about 30 lines that hand it the AWS-signed token;
  • Python, with the token exchange written by hand against Microsoft’s documented agent protocol (about 60 lines).

Both were deployed side by side on AgentCore Runtime and passed the same checks: caller validated before the container ran, an app-only token as the agent, an on-behalf-of token for the user, an Agent 365 telemetry token, and an unapproved agent identity blocked by Conditional Access.

As in the earlier article, the focus is the calls and the configuration, in the order they have to be made, and why. Hosting details beyond what AgentCore requires are left out.

Status of the APIs. Entra Agent ID, the Agent 365 SDKs and CLI, Conditional Access for agents and AgentCore’s inbound JWT authorization were in preview or recently released when this was written (October 2026). Names, permissions, defaults and endpoints may change; check the current Microsoft and AWS documentation before relying on them.

Licensing and availability. Microsoft licensing for Agent 365, Entra Agent ID, Conditional Access for agents, Purview and Defender is complex and changes often, and some capabilities depend on preview enrolment (the Agent 365 CLI, for example, expects the tenant to be in the Frontier program). Nothing in this article is licensing advice. Confirm what your tenant needs, and what is available to it, with your Microsoft account team before you plan or build.

Conventions

Values in angle brackets are placeholders: <tenant-id>, <aws-account-id>, <blueprint-app-id>, <agent-identity-id>, <orders-api-app-id> and so on. Nothing in this article is specific to one environment.

Constants published by Microsoft, the same in every tenant:

ConstantValue
Token-exchange audience (AWS token and exchange scope)api://AzureADTokenExchange
Agent 365 observability API9b975845-388f-4429-889e-eab1ef63949c
Azure CLI client application (used to pre-authorize callers)04b07795-8ddb-461a-bbee-02f9e1bf7b46
“Default access” app role00000000-0000-0000-0000-000000000000

The examples call a protected “orders” API (api://<orders-api-app-id>) that exposes a delegated scope Orders.Read and an application role Orders.Read.All. Substitute whatever your agent calls.

The idea in one paragraph

Nothing about the trust changes. AWS still signs a short-lived JWT that says “this is IAM role X in account Y”; the agent’s Entra blueprint still trusts exactly that issuer and subject through a federated identity credential. What changes is who runs the exchange. Instead of a sidecar reading a token file, the agent asks AWS STS for the token at the moment it needs one, presents it to Entra as the blueprint’s credential to get an exchange token for its agent identity, and then uses that to get the token it actually needs: as itself (app-only) or for the user who called it (on-behalf-of).

Sidecar or in-process: what moves where

ConcernECS with the sidecarAgentCore Runtime, in-process
ContainersAgent + Entra auth sidecar + token helperAgent only
AWS-signed tokenToken helper writes it to a shared file every 10 minutesAgent calls sts:GetWebIdentityToken when Entra needs a fresh assertion
Blueprint credential settingSignedAssertionFilePath.NET: CustomSignedAssertion provider; Python: the token itself as client_assertion
Caller validationSidecar /ValidateAgentCore custom JWT authorizer, before the container runs (and optionally again in the agent)
Caller token inside the agentThe request headerForwarded only if the runtime allowlists the Authorization header
Agent tokensSidecar /AuthorizationHeader... endpoints.NET: WithAgentIdentity(...); Python: three HTTP posts to the Entra token endpoint
Who maintains the protocol codeMicrosoft (sidecar image).NET: Microsoft (Microsoft.Identity.Web). Python: you
Federated credential subjectECS task role ARNAgentCore execution role ARN
Telemetry to Agent 365Same package, token from the sidecarSame package, token from the in-process exchange

The last row is the reassuring one, with one caveat. Agent 365 observability, Conditional Access for agents, sign-in logs and the audit trail in Purview and Defender don’t care where the token exchange runs. They are not automatic, though: observability still has to be switched on with the Graph grant in Phase 2.2 and the SDK setup in Phase 4.3. Moving the exchange in-process changes neither of those; it just changes who fetches the tokens.

The moving parts

PartWhat it is
AWS IAM outbound identity federationAccount-level feature; IAM principals can call sts:GetWebIdentityToken and get a JWT signed by the account’s own issuer.
AgentCore execution roleThe IAM role the runtime assumes. Its ARN is the subject of the AWS-signed token.
AgentCore RuntimeHosts one arm64 container serving POST /invocations and GET /ping on port 8080. Its custom JWT authorizer validates callers; its request header allowlist decides which headers reach the container.
Agent identity blueprintEntra application of type agentIdentityBlueprint. Holds the federated credential; parent of the agent identity; the audience of callers’ tokens.
Agent identityService principal of type agentIdentity: who the agent is in Entra, Conditional Access and Agent 365.
Token exchange code.NET: Microsoft.Identity.Web 4.16.1 + Microsoft.Identity.Web.AgentIdentities + a custom signed-assertion provider. Python: boto3 + httpx.
Agent 365 observability SDKmicrosoft-opentelemetry[langchain], exactly as in the sidecar article.

The token flow

Request flow: LangChain agent on Amazon Bedrock AgentCore Runtime with Microsoft Entra, no sidecar. The shaded steps replace the token helper and the auth sidecar; they are described in the sections below.

In short:

Show codeHide code13 lines
caller --(Entra token, aud = blueprint)--> AgentCore custom JWT authorizer  [rejects before the container runs]
                                               |
                                               v  Authorization header (allowlisted)
                                           agent container
  0. AWS STS  GetWebIdentityToken (aud api://AzureADTokenExchange, RS256, 300 s)  -> AWS-signed JWT
  1. Entra    blueprint, client_credentials, fmi_path = <agent-identity-id>,
              client_assertion = AWS JWT, scope api://AzureADTokenExchange/.default -> T1
  2a. Entra   agent identity, client_credentials, client_assertion = T1           -> app-only token (roles)
  2b. Entra   agent identity, jwt-bearer on_behalf_of, assertion = caller token,
              client_assertion = T1                                                -> delegated token (scp, oid = user)
                                               |
                                               v
                                   orders API / MCP gateway / Agent 365

Step 1 is the part the sidecar used to hide. fmi_path tells Entra which of the blueprint’s agent identities the exchange token is for; the result (T1) is only usable as a client assertion by that one agent identity.

Prerequisites

  • An AWS account in a region where AgentCore Runtime is available, with Amazon Bedrock model access for your model.
  • Container images built for arm64. AgentCore Runtime runs arm64; build with docker buildx --platform linux/arm64 (QEMU on an x86 build machine is fine).
  • A Microsoft tenant with Entra Agent ID and Agent 365 available, and the licensing they require (see the note above).
  • A sponsor for the agent (a user), and an administrator who can grant API permissions and create Conditional Access policies.
  • One of:
    • the Agent 365 CLI (a365, a .NET tool; it needs PowerShell 7 on the machine running it), or

    • an identity for the deployment pipeline with these Microsoft Graph application permissions (admin consent required), to create the blueprint and agent identity yourself:

      Show codeHide code12 lines
      AgentIdentityBlueprint.Create
      AgentIdentityBlueprint.Read.All
      AgentIdentityBlueprint.AddRemoveCreds.All
      AgentIdentityBlueprint.UpdateAuthProperties.All
      AgentIdentityBlueprint.DeleteRestore.All
      AgentIdentityBlueprintPrincipal.Create
      AgentIdentityBlueprintPrincipal.Read.All
      AgentIdentityBlueprintPrincipal.DeleteRestore.All
      AgentIdentity.Create.All
      AgentIdentity.Read.All
      AgentIdentity.DeleteRestore.All
      AgentRegistration.ReadWrite.All

      The Phase 2 steps need more: AppRoleAssignment.ReadWrite.All and AgentIdentityBlueprintPrincipal.ReadWrite.All. Keep those with an administrator instead of the pipeline. (Graph examples use az rest, which signs with the signed-in identity; any HTTP client with a Graph token works the same way.)

  • Library versions that were tested together:
Python.NET
bedrock-agentcore==1.24.1Microsoft.Identity.Web 4.16.1
boto3==1.43.111 (1.24.1 needs a recent boto3; older pins conflict)Microsoft.Identity.Web.AgentIdentities 4.16.1
httpx==0.28.1AWSSDK.SecurityToken 4.0.101.3
microsoft-opentelemetry[langchain]==1.3.9.NET 8

Phase 0: Prepare AWS (once per account, once per agent)

0.1 Enable outbound identity federation

aws iam enable-outbound-web-identity-federation
aws iam get-outbound-web-identity-federation-info   # note the issuer URL

Same as for ECS. If you already did this for the sidecar pattern, there is nothing to do: the issuer is per account.

0.2 Create the AgentCore execution role

Trust policy: AgentCore assumes the role, only for your account.

Show codeHide codejson · 9 lines
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "bedrock-agentcore.amazonaws.com" },
    "Action": "sts:AssumeRole",
    "Condition": { "StringEquals": { "aws:SourceAccount": "<aws-account-id>" } }
  }]
}

Permissions: the model, the image, logs, and one federation statement.

Show codeHide codejson · 18 lines
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "Model", "Effect": "Allow",
      "Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
      "Resource": ["arn:aws:bedrock:<region>:<aws-account-id>:inference-profile/<inference-profile-id>",
                   "arn:aws:bedrock:*::foundation-model/<foundation-model-id>"] },
    { "Sid": "Image", "Effect": "Allow",
      "Action": ["ecr:GetAuthorizationToken", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"],
      "Resource": "*" },
    { "Sid": "Logs", "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], "Resource": "*" },
    { "Sid": "EntraFederationAssertion", "Effect": "Allow",
      "Action": "sts:GetWebIdentityToken", "Resource": "*",
      "Condition": { "ForAllValues:StringEquals": {
        "sts:IdentityTokenAudience": ["api://AzureADTokenExchange"] } } }
  ]
}

Why: the federation statement is the only thing that lets this workload speak to Entra, and the condition limits it to the token-exchange audience. Note the role ARN: it is the subject Entra will trust. Keep the name stable.

Phase 1: Register the agent in Entra and Agent 365

You need a blueprint, an agent identity and a registry entry. There are two ways to get them.

1.1 Option A: the Agent 365 CLI

a365 setup all --agent-name <agent-name>

With no project folder and no messaging endpoint, the CLI creates:

  1. a blueprint (<agent-name> Blueprint), its service principal, with you as sponsor and owner;
  2. a delegated scope access_agent_as_user on the blueprint (not access_agent as in the hand-built version);
  3. inheritable permissions for Microsoft Graph, Agent 365 Tools and the Power Platform API, with admin consent (a browser window opens);
  4. an agent identity (<agent-name> Identity);
  5. a registration in the Agent 365 registry (<agent-name> Agent), linked to both.

It skips the messaging endpoint step for an agent that isn’t a Microsoft 365 channel agent, which is right for an AgentCore agent that is called by API.

Remove the secret it creates. The CLI also adds a client secret to the blueprint (display name “Agent 365 CLI Generated Secret”, two-year lifetime) and prints it in its output. The whole point of this pattern is that no secret exists. Once the federated credential in step 1.3 is working, delete it:

az ad app credential list   --id <blueprint-app-id> --query "[].{name:displayName, keyId:keyId}"
az ad app credential delete --id <blueprint-app-id> --key-id <key-id>

and treat any terminal transcript or log that captured the CLI output as sensitive.

1.2 Option B: Microsoft Graph

These are the same calls as steps 1.1–1.6 of the AWS sidecar article, copied here so you don’t have to switch articles. Nothing in them is ECS-specific except the federated credential, which for AgentCore trusts the execution role — step 1.3 below. The order is fixed: each call needs an id from an earlier one.

a. Create the agent identity blueprint. The @odata.type is what makes this a blueprint and not an ordinary app registration. Save id (object id) and appId.

Show codeHide codebash · 6 lines
az rest --method POST --url "https://graph.microsoft.com/v1.0/applications" \
  --headers "Content-Type=application/json" --body '{
    "@odata.type": "#microsoft.graph.agentIdentityBlueprint",
    "displayName": "<agent-name>-blueprint",
    "sponsors@odata.bind": ["https://graph.microsoft.com/v1.0/users/<sponsor-object-id>"]
  }'

b. Expose an API on the blueprint — the scope callers request tokens for. (A hand-built blueprint uses access_agent; the CLI uses access_agent_as_user.)

Show codeHide codebash · 11 lines
az rest --method PATCH --url "https://graph.microsoft.com/v1.0/applications/<blueprint-object-id>" \
  --headers "Content-Type=application/json" --body '{
    "identifierUris": ["api://<blueprint-app-id>"],
    "api": { "oauth2PermissionScopes": [{
      "id": "<new-guid>", "value": "access_agent", "type": "User", "isEnabled": true,
      "adminConsentDisplayName": "Access <agent-name>",
      "adminConsentDescription": "Allow the application to call <agent-name> on behalf of the signed-in user.",
      "userConsentDisplayName": "Access <agent-name>",
      "userConsentDescription": "Allow the application to call <agent-name> on your behalf."
    }]}
  }'

Then pre-authorize the client applications users sign in with (here the Azure CLI). The api block is replaced whole on each PATCH, so repeat the scope:

Show codeHide codebash · 10 lines
az rest --method PATCH --url "https://graph.microsoft.com/v1.0/applications/<blueprint-object-id>" \
  --headers "Content-Type=application/json" --body '{
    "api": {
      "oauth2PermissionScopes": [ { "...": "the same scope object as above" } ],
      "preAuthorizedApplications": [{
        "appId": "04b07795-8ddb-461a-bbee-02f9e1bf7b46",
        "delegatedPermissionIds": ["<the-scope-guid>"]
      }]
    }
  }'

c. Create the blueprint principal — the service principal that access assignments and the agent identity both need. Entra is eventually consistent, so retry on Request_ResourceNotFound or NoBackingApplicationObject.

Show codeHide codebash · 5 lines
az rest --method POST --url "https://graph.microsoft.com/v1.0/servicePrincipals" \
  --headers "Content-Type=application/json" --body '{
    "@odata.type": "#microsoft.graph.agentIdentityBlueprintPrincipal",
    "appId": "<blueprint-app-id>"
  }'

d. Add the federated credential — the one call that differs from ECS. Use step 1.3 below (the AgentCore execution role), not the ECS task role.

e. Create the agent identity — who the agent acts as. Fails until the blueprint principal (c) exists; save the returned id as <agent-identity-id>.

Show codeHide codebash · 7 lines
az rest --method POST --url "https://graph.microsoft.com/v1.0/servicePrincipals" \
  --headers "Content-Type=application/json" --body '{
    "@odata.type": "#microsoft.graph.agentIdentity",
    "displayName": "<agent-name>",
    "agentIdentityBlueprintId": "<blueprint-app-id>",
    "sponsors@odata.bind": ["https://graph.microsoft.com/v1.0/users/<sponsor-object-id>"]
  }'

f. Register the agent in the Agent 365 registry — lists it in the Microsoft 365 admin center and ties the entry to the Entra identity (the link that makes it a managed agent, not just a listed one).

Show codeHide codebash · 20 lines
az rest --method POST --url "https://graph.microsoft.com/beta/copilot/agentRegistrations" \
  --headers "Content-Type=application/json" --body '{
    "displayName": "<agent-name>",
    "description": "LangChain chat agent on Amazon Bedrock AgentCore",
    "createdBy": "<sponsor-object-id>",
    "ownerIds": ["<sponsor-object-id>"],
    "sourceAgentId": "<agent-name>",
    "originatingStore": "<how-it-was-created>",
    "sourceCreatedDateTime": "<utc-timestamp>",
    "sourceLastModifiedDateTime": "<utc-timestamp>",
    "agentIdentityBlueprintId": "<blueprint-app-id>",
    "agentIdentityId": "<agent-identity-id>",
    "agentCard": {
      "name": "<agent-name>", "version": "1.0.0",
      "description": "General-purpose chat assistant built with LangChain, hosted on AWS.",
      "capabilities": { "streaming": false, "pushNotifications": false },
      "defaultInputModes": ["text"], "defaultOutputModes": ["text"],
      "skills": [{ "id": "chat", "name": "Chat", "description": "Answers general questions." }]
    }
  }'

You can also reuse an existing blueprint (for example the ECS agent’s) and just add a second federated credential for the AgentCore role. That gives both workloads the same agent identity. A blueprint per hosting platform is easier to reason about in sign-in logs and Agent 365; a shared one is fewer objects. Both work.

1.3 Trust the AgentCore execution role (the key call)

Show codeHide codebash · 9 lines
az rest --method POST \
  --url "https://graph.microsoft.com/v1.0/applications/<blueprint-object-id>/federatedIdentityCredentials" \
  --headers "Content-Type=application/json" --body '{
    "name": "aws-agentcore-execution-role",
    "description": "AWS IAM outbound identity federation: AgentCore Runtime execution role",
    "issuer": "https://<issuer-id>.tokens.sts.global.api.aws",
    "subject": "arn:aws:iam::<aws-account-id>:role/<execution-role-name>",
    "audiences": ["api://AzureADTokenExchange"]
  }'

Order: before the runtime’s first invocation. If you deploy with Terraform, make the runtime depend on this resource.

Details that matter: issuer, subject and audience must match the AWS token exactly, including case. An application can hold a limited number of federated credentials (20 at the time of writing), so one per workload role is fine, one per deployment is not.

Phase 2: Govern what the agent may do (Entra administrator)

These are the same controls as for any agent identity. Each one was verified from inside the AgentCore runtime.

2.1 Grant the agent identity access to the downstream API

App-only (the agent acting as itself), an app role assignment:

az rest --method POST --headers "Content-Type=application/json" \
  --url "https://graph.microsoft.com/v1.0/servicePrincipals/<orders-api-sp-id>/appRoleAssignedTo" \
  --body '{ "principalId": "<agent-identity-id>", "resourceId": "<orders-api-sp-id>",
            "appRoleId": "<Orders.Read.All-role-id>" }'

On behalf of a user, a delegated permission grant:

az rest --method POST --headers "Content-Type=application/json" \
  --url "https://graph.microsoft.com/v1.0/oauth2PermissionGrants" \
  --body '{ "clientId": "<agent-identity-id>", "consentType": "AllPrincipals",
            "resourceId": "<orders-api-sp-id>", "scope": "Orders.Read" }'

Why both: they are different paths with different claims. App-only tokens carry roles and are evaluated by Conditional Access for agents; on-behalf-of tokens carry scp, name the user in oid and the agent in azp, and are evaluated by the user’s policies. Grant only the one(s) the agent uses.

2.2 Let the agent identity send telemetry

Assign Agent365.Observability.OtelWrite on the Agent 365 observability API (9b975845-...) to the agent identity. Agent 365 accepts telemetry only from an identity holding that role. (Same call as step 2.4 of the sidecar article.)

Show codeHide codebash · 10 lines
az ad sp show --id 9b975845-388f-4429-889e-eab1ef63949c \
  --query "{resourceId:id, role:appRoles[?value=='Agent365.Observability.OtelWrite'].id | [0]}"

az rest --method POST --headers "Content-Type=application/json" \
  --url "https://graph.microsoft.com/v1.0/servicePrincipals/<observability-sp-id>/appRoleAssignedTo" \
  --body '{
    "principalId": "<agent-identity-id>",
    "resourceId": "<observability-sp-id>",
    "appRoleId": "<otelwrite-role-id>"
  }'

Order: before the runtime first starts. The in-process exchange caches tokens, so one issued before the grant carries no role until it is refreshed or the container restarts.

2.3 Conditional Access for agents

Mark approved agents with a custom security attribute (for example AgentGovernance/Approval = Approved) and create a Conditional Access policy that blocks agent identities without it. An agent identity that isn’t approved then fails at step 2a with AADSTS53003, from inside AgentCore exactly as from anywhere else. Test it with a second, unapproved agent identity before you rely on it.

2.4 Decide who may call the agent

Assign users or a group to the blueprint principal, then set appRoleAssignmentRequired to true. Entra then refuses tokens for the agent to anyone not assigned (AADSTS50105), before a request reaches AWS. (Same calls as steps 2.2–2.3 of the sidecar article.)

Show codeHide codebash · 9 lines
az ad group create --display-name "<agent-users-group>" --mail-nickname "<agent-users-group>"

az rest --method POST --headers "Content-Type=application/json" \
  --url "https://graph.microsoft.com/v1.0/servicePrincipals/<blueprint-principal-id>/appRoleAssignedTo" \
  --body '{
    "principalId": "<group-object-id>",
    "resourceId": "<blueprint-principal-id>",
    "appRoleId": "00000000-0000-0000-0000-000000000000"
  }'

Then require assignment (do this after the grant above, or you lock out your own callers):

az rest --method PATCH --headers "Content-Type=application/json" \
  --url "https://graph.microsoft.com/v1.0/servicePrincipals/<blueprint-principal-id>/microsoft.graph.agentIdentityBlueprintPrincipal" \
  --body '{ "appRoleAssignmentRequired": true }'

Phase 3: Configure the AgentCore runtime

Two settings do the work the sidecar’s /Validate endpoint did.

3.1 Custom JWT authorizer: Entra, v2

Show codeHide codehcl · 31 lines
resource "aws_bedrockagentcore_agent_runtime" "agent" {
  agent_runtime_name = "<agent_name>"
  role_arn           = aws_iam_role.runtime.arn

  agent_runtime_artifact {
    container_configuration { container_uri = "<ecr-image-uri-arm64>" }
  }
  network_configuration { network_mode = "PUBLIC" }

  authorizer_configuration {
    custom_jwt_authorizer {
      discovery_url    = "https://login.microsoftonline.com/<tenant-id>/v2.0/.well-known/openid-configuration"
      allowed_audience = ["<blueprint-app-id>", "api://<blueprint-app-id>"]
      # Not allowed_clients: AgentCore matches it against a client_id claim, which Entra tokens don't carry
      # (Entra uses azp / appid). Restrict client apps with Entra pre-authorization instead.
    }
  }

  request_header_configuration {
    request_header_allowlist = ["Authorization"]
  }

  environment_variables = {
    AZURE_TENANT_ID    = "<tenant-id>"
    AGENT_BLUEPRINT_ID = "<blueprint-app-id>"
    AGENT_IDENTITY_ID  = "<agent-identity-id>"
    ORDERS_SCOPE       = "api://<orders-api-app-id>/.default"
  }

  depends_on = [aws_iam_role_policy.runtime, msgraph_resource.blueprint_fic]
}

(AWS provider 6.67 was used; the console and aws bedrock-agentcore-control create-agent-runtime take the same settings.)

Why v2: blueprints issue v2 access tokens: iss is https://login.microsoftonline.com/<tenant-id>/v2.0 and aud is the bare blueprint app ID. AgentCore compares the token’s issuer with the discovery document’s. With the v1 discovery URL every call fails with Claim 'iss' value mismatch. Listing both audience forms costs nothing.

What you get: a call without a valid token is rejected by AgentCore (AWS documents 401 with a WWW-Authenticate header for a missing bearer token; I also saw 403 for a request that carried no credentials at all) and the container never runs. That is a stronger position than the sidecar’s, where the agent itself had to call /Validate first.

3.2 Header allowlist: forward the caller’s token

By default the container doesn’t see the caller’s Authorization header. The allowlist above forwards it; the Python SDK exposes it as context.request_headers. Without it, step 2b (on-behalf-of) is impossible, because the agent has no user token to exchange. App-only works either way.

3.3 Packaging and deploying the code

The token-exchange code in Phase 4 isn’t injected at runtime; it’s part of the agent’s container image, the same for .NET and Python. Full hosting (CI/CD, networking) is out of scope, but the shape is:

  • Add the code to your agent project (the Python module, or the .NET provider classes), then build the image for arm64 and push it to ECR (docker buildx build --platform linux/arm64 ... --push, or let the AgentCore Starter Toolkit build it with agentcore configure / agentcore launch).
  • Point the runtime at that image (container_uri) and set the non-secret environment_variables from §3.1.

To update the code, build a new image tag, push it, and move the runtime to it — there is no in-place patching of a running container:

aws bedrock-agentcore-control update-agent-runtime \
  --agent-runtime-id <id> \
  --agent-runtime-artifact '{"containerConfiguration":{"containerUri":"<ecr-image-uri-arm64:new-tag>"}}'

…or re-apply Terraform with the new container_uri, or re-run agentcore launch. AgentCore cuts a new version and new invocations run the new image. The JWT authorizer and header allowlist (§3.1–3.2) are runtime configuration, not code, so a code change alone doesn’t touch them.

Phase 4: The token exchange in code

4.1 .NET: Microsoft.Identity.Web does the protocol

Microsoft.Identity.Web already implements the agent identity protocol (steps 1, 2a and 2b). The only missing piece is where the blueprint’s credential comes from. A custom signed-assertion provider supplies it from AWS STS:

Show codeHide codecsharp · 27 lines
public sealed class AwsStsSignedAssertionLoader(IAmazonSecurityTokenService sts) : ICustomSignedAssertionProvider
{
    public string Name => "AwsSts";
    public CredentialSource CredentialSource => CredentialSource.CustomSignedAssertion;

    public Task LoadIfNeededAsync(CredentialDescription credentialDescription,
                                  CredentialSourceLoaderParameters? parameters = null)
    {
        credentialDescription.CachedValue ??= new AwsStsAssertion(sts);
        return Task.CompletedTask;
    }
}

// Called when Entra needs a fresh assertion; the base class caches it until it expires.
public sealed class AwsStsAssertion(IAmazonSecurityTokenService sts) : ClientAssertionProviderBase
{
    protected override async Task<ClientAssertion> GetClientAssertionAsync(AssertionRequestOptions? options)
    {
        var resp = await sts.GetWebIdentityTokenAsync(new GetWebIdentityTokenRequest
        {
            Audience = ["api://AzureADTokenExchange"],
            SigningAlgorithm = "RS256",   // the only algorithm Entra accepts here
            DurationSeconds = 300,        // see lessons learned: longer fails inside AgentCore
        });
        return new ClientAssertion(resp.WebIdentityToken, resp.Expiration);
    }
}

Wire it up with the same AzureAd settings the sidecar used, except the credential source:

Show codeHide codecsharp · 14 lines
builder.Services.AddSingleton<IAmazonSecurityTokenService>(_ => new AmazonSecurityTokenServiceClient());
builder.Services.AddSingleton<ICustomSignedAssertionProvider, AwsStsSignedAssertionLoader>();

builder.Configuration["AzureAd:Instance"] = "https://login.microsoftonline.com/";
builder.Configuration["AzureAd:TenantId"] = tenantId;
builder.Configuration["AzureAd:ClientId"] = blueprintAppId;   // the blueprint is the client
builder.Configuration["AzureAd:ClientCredentials:0:SourceType"] = "CustomSignedAssertion";
builder.Configuration["AzureAd:ClientCredentials:0:CustomSignedAssertionProviderName"] = "AwsSts";
// Do NOT set AzureAd:Audience (see lessons learned).

builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration, "AzureAd")
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();
builder.Services.AddAgentIdentities();

AddMicrosoftIdentityWebApiAuthentication validates the forwarded caller token a second time (defence in depth behind AgentCore’s authorizer) and keeps it for on-behalf-of. Then, in the handler:

Show codeHide codecsharp · 7 lines
// As the agent (app-only; Conditional Access for agents applies)
var appHeader = await headers.CreateAuthorizationHeaderForAppAsync(
    ordersScope, new AuthorizationHeaderProviderOptions().WithAgentIdentity(agentIdentityId));

// On behalf of the validated caller
var oboHeader = await headers.CreateAuthorizationHeaderForUserAsync(
    [ordersScope], new AuthorizationHeaderProviderOptions().WithAgentIdentity(agentIdentityId), http.User);

That is the whole .NET change: one class pair and one configuration line compared with the sidecar’s SignedAssertionFilePath.

4.2 Python: the protocol by hand

At the time of writing I found no supported Python library that performs the agent identity exchange in-process; Microsoft’s route for Python and other non-.NET languages is the sidecar. Without one, the exchange is three posts to the Entra token endpoint. Keep it in one small module with an in-memory cache.

Show codeHide codepython · 59 lines
import base64, json, os, threading, time
import boto3, httpx

TENANT_ID = os.environ["AZURE_TENANT_ID"]
BLUEPRINT_APP_ID = os.environ["AGENT_BLUEPRINT_ID"]
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
ASSERTION = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
SKEW = 300

_sts = boto3.client("sts", region_name=os.environ.get("AWS_REGION"))
_http = httpx.Client(timeout=20)
_lock, _cache = threading.Lock(), {}

def _exp(token):
    p = token.split(".")[1]; p += "=" * (-len(p) % 4)
    return float(json.loads(base64.urlsafe_b64decode(p))["exp"])

def _cached(key, fetch):
    with _lock:
        hit = _cache.get(key)
        if hit and hit[1] - SKEW > time.time():
            return hit[0]
    token = fetch()
    with _lock:
        _cache[key] = (token, _exp(token))
    return token

def _post(form):
    r = _http.post(AUTHORITY, data=form)
    if r.status_code != 200:   # surface AADSTS codes, never tokens
        body = r.json()
        raise PermissionError(f"Entra {r.status_code} {body.get('error_codes')} {body.get('error_description', '')[:300]}")
    return r.json()["access_token"]

def aws_assertion():
    """Step 0. Not cached: short-lived, used once to get T1."""
    return _sts.get_web_identity_token(Audience=["api://AzureADTokenExchange"],
                                       SigningAlgorithm="RS256", DurationSeconds=300)["WebIdentityToken"]

def exchange_token(agent_identity):
    """Step 1. T1: the blueprint, for one of its agent identities."""
    return _cached(("t1", agent_identity), lambda: _post({
        "client_id": BLUEPRINT_APP_ID, "grant_type": "client_credentials",
        "scope": "api://AzureADTokenExchange/.default", "fmi_path": agent_identity,
        "client_assertion_type": ASSERTION, "client_assertion": aws_assertion()}))

def app_token(agent_identity, scope):
    """Step 2a. As the agent itself."""
    return _cached(("app", agent_identity, scope), lambda: _post({
        "client_id": agent_identity, "grant_type": "client_credentials", "scope": scope,
        "client_assertion_type": ASSERTION, "client_assertion": exchange_token(agent_identity)}))

def obo_token(agent_identity, user_token, scope):
    """Step 2b. On behalf of the caller; the user token's aud must be the blueprint."""
    return _cached(("obo", agent_identity, scope, user_token[-32:]), lambda: _post({
        "client_id": agent_identity, "scope": scope,
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion": user_token, "requested_token_use": "on_behalf_of",
        "client_assertion_type": ASSERTION, "client_assertion": exchange_token(agent_identity)}))

The AgentCore entry point picks the mode and passes a token function to the LangChain tools:

Show codeHide codepython · 20 lines
from bedrock_agentcore.runtime import BedrockAgentCoreApp
app = BedrockAgentCoreApp()

@app.entrypoint
def invoke(payload, context):
    headers = getattr(context, "request_headers", None) or {}
    auth = headers.get("Authorization") or headers.get("authorization") or ""
    user_token = auth.split(" ", 1)[1] if auth.lower().startswith("bearer ") else ""

    if payload.get("mode") == "autonomous":
        token_for_orders = lambda: app_token(AGENT_IDENTITY_ID, ORDERS_SCOPE)
    else:
        if not user_token:
            return {"error": "no caller token: check the JWT authorizer and the header allowlist"}
        token_for_orders = lambda: obo_token(AGENT_IDENTITY_ID, user_token, ORDERS_SCOPE)

    with telemetry.invoke_scope(payload["prompt"], getattr(context, "session_id", None), user_token):
        result = build_agent(token_for_orders).invoke(
            {"messages": [{"role": "user", "content": payload["prompt"]}]})
    return {"reply": result["messages"][-1].content}

Details that matter:

  • Tokens live in process memory only: never on disk, never in logs. Log error codes, not responses.
  • Cache T1 and the downstream tokens; don’t cache the AWS assertion.
  • The on-behalf-of cache key must include something unique to the user token, or one user’s token could be served to another.
  • Microsoft recommends its SDKs over hand-written protocol code. This works, but it is your code to keep in step with the protocol. If you have the choice of language for an AgentCore agent, the .NET path carries less of that burden.

4.3 Telemetry: the same SDK, a different token source

Enabling observability takes these calls — none of it is automatic. Register the agent in the Agent 365 registry (§1.6); grant the agent identity Agent365.Observability.OtelWrite (§2.2); then, in code, call use_microsoft_opentelemetry(...) with the agent-identity token resolver and wrap each request in an invoke_agent span (below). enable_sensitive_data=True is what records prompts and responses. Tenant eligibility (licensing and enrolment) is a separate, tenant-wide prerequisite — confirm it with your Microsoft account team.

Agent 365 observability is set up as in the sidecar article; only the token resolver changes. The install and pin:

microsoft-opentelemetry[langchain]

Pin exact versions of this package and of langchain, langchain-core, langgraph and langchain-aws, and re-test when you bump them: the LangChain instrumentation is version-sensitive and fails silently when it doesn’t attach. Then switch telemetry on before the app and LangChain objects exist (objects created earlier are not instrumented):

Show codeHide codepython · 13 lines
A365_SCOPE = "api://9b975845-388f-4429-889e-eab1ef63949c/.default"

def _resolver(agent_id, tenant_id):
    return app_token(agent_id, A365_SCOPE)      # cached; called from the exporter thread

use_microsoft_opentelemetry(
    resource=Resource.create({"service.name": AGENT_NAME, "cloud.provider": "aws",
                              "cloud.platform": "aws_bedrock_agentcore"}),
    enable_a365=True, a365_enable_observability_exporter=True,
    a365_use_s2s_endpoint=True, a365_token_resolver=_resolver,
    a365_exporter_storage_directory="/tmp/otel/a365",   # the image's working dir may be read-only
    enable_sensitive_data=True,
)

AgentCore also runs its own OpenTelemetry pipeline for CloudWatch. Install Microsoft’s tracer provider first (import the telemetry module before anything else) and keep to one global provider, or spans end up in one place and not the other.

The telemetry.invoke_scope(...) used in the entry point above wraps each request in an invoke_agent span — the root span Agent 365 keys on. Its body is the same as step 4.4 of the sidecar article:

Show codeHide codepython · 22 lines
from microsoft.opentelemetry.a365.core import (
    AgentDetails, BaggageBuilder, CallerDetails, Channel,
    InvokeAgentScope, InvokeAgentScopeDetails, Request, UserDetails)

AGENT = AgentDetails(agent_id=AGENT_IDENTITY_ID, agent_name=AGENT_NAME,
                     agent_blueprint_id=BLUEPRINT_APP_ID, tenant_id=TENANT_ID,
                     agent_version=APP_VERSION, provider_name="LangChain")

baggage = (BaggageBuilder()
           .tenant_id(TENANT_ID).agent_id(AGENT_IDENTITY_ID).agent_blueprint_id(BLUEPRINT_APP_ID)
           .conversation_id(conversation_id).session_id(session_id)
           .user_id(claims["oid"]).user_email(claims.get("preferred_username"))
           .build())
request = Request(content=message, session_id=session_id,
                  conversation_id=conversation_id, channel=Channel(name="http-api"))
caller = CallerDetails(user_details=UserDetails(user_id=claims["oid"],
                                                user_email=claims.get("preferred_username")))

with baggage, InvokeAgentScope.start(request, InvokeAgentScopeDetails(), AGENT, caller) as scope:
    scope.record_input_messages(message)
    result = agent.invoke({"messages": [{"role": "user", "content": message}]}, config)
    scope.record_output_messages(reply_text)

BaggageBuilder copies the identity attributes onto every child span, so each model and tool call is attributed to the same agent, tenant, conversation and caller. To confirm the tenant accepts the telemetry, set the logger microsoft.opentelemetry.a365.core.exporters.agent365_exporter to DEBUG: each export logs an HTTP status and a per-destination "status": "sent" in CloudWatch — the direct evidence it left AWS.

Where it shows up (after the usual ingestion delay):

PlaceWhat to look for
Microsoft 365 admin center > AgentsThe agent’s registry entry and activity
Microsoft Purview > DSPM > AI observability, and AuditInteractions, prompts and responses, by agent and by user
Microsoft Defender > Advanced huntingCloudAppEvents with action types InvokeAgent, InferenceCall, ExecuteToolBySDK

Phase 5: Call it

Show codeHide codebash · 8 lines
TOKEN=$(az account get-access-token --scope "api://<blueprint-app-id>/access_agent_as_user" \
        --query accessToken -o tsv)          # access_agent if you built the blueprint yourself

curl -s -X POST \
  "https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-runtime-arn>/invocations?qualifier=DEFAULT" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: <33+-character-session-id>" \
  -d '{"prompt": "List the orders", "mode": "user"}'

With a JWT authorizer configured, callers use a bearer token, not SigV4 (a runtime accepts one or the other, not both). Without the header the runtime rejects the call and the container never runs.

How to know it worked

Give the agent a diagnostic mode that performs each step and returns decoded claims only, never tokens. These are the claims to check:

StepClaim check
Caller (forwarded header)aud = blueprint app ID, iss ends in /v2.0, scp = your agent scope
AWS assertioniss = the account issuer, sub = the execution role ARN, aud = api://AzureADTokenExchange
T1azp = blueprint, sub ends with the agent identity ID
App-only tokenoid = azp = agent identity, roles contains the app role, idtyp = app
On-behalf-of tokenoid = the user, azp = agent identity, scp contains the delegated scope
Agent 365 tokenroles = Agent365.Observability.OtelWrite
Unapproved agent identityAADSTS53003 (blocked by Conditional Access)

Then confirm outside the agent: Entra sign-in logs → Agent sign-ins show the agent identity (the agent type column tells blueprint, agent identity and agent user sign-ins apart), the Agent 365 registry shows the agent, and Defender advanced hunting shows CloudAppEvents for it after the usual ingestion delay.

The order, and what breaks if you change it

#StepMust come afterIf skipped or out of order
1Enable AWS outbound identity federation—No issuer; GetWebIdentityToken is denied
2Execution role with sts:GetWebIdentityToken1No subject for Entra to trust
3Blueprint, principal, agent identity, registry (CLI or Graph)—Nothing to federate to, nothing to act as
4Federated credential: issuer + execution role ARN1, 2, 3Step 1 of the exchange fails (AADSTS70021, no matching federated identity record)
5Delete the CLI-generated client secret4 workingA two-year secret exists for an agent that needs none
6API permissions, OtelWrite, approval attribute3On-behalf-of fails for lack of consent; app-only tokens have no roles; telemetry rejected; Conditional Access blocks the agent
7Runtime with v2 JWT authorizer and header allowlist3, 4iss mismatch on every call; no on-behalf-of
8Telemetry set up before LangChain objects are created—Missing model and tool spans
9Per request: caller token → T1 → app-only or on-behalf-of7—

Lessons learned

1. Use the v2 discovery document. Blueprint tokens are v2. AgentCore’s authorizer checks the issuer against the discovery document, so the v1 URL fails every call with Claim 'iss' value mismatch. Put both <app-id> and api://<app-id> in the allowed audiences, and leave allowedClients empty: AWS matches it against a client_id claim, and Entra tokens carry the client in azp, so setting it would reject every Entra caller.

2. Ask AWS for a 300-second token. Inside AgentCore Runtime, GetWebIdentityToken with the 3600 seconds used on ECS fails with SessionDurationEscalationException: the web identity token may not outlive the runtime’s own session credentials. Five minutes is plenty, because the token is used once, to get T1, and T1 is then cached for its own lifetime.

3. Don’t set AzureAd:Audience in .NET. With it set to api://<blueprint>, Microsoft.Identity.Web rejects the v2 token, whose audience is the bare app ID (401 with no obvious reason). Leave it unset; the defaults accept both forms.

4. The header allowlist is not optional for on-behalf-of. AgentCore validates the caller and then, by default, drops the header. App-only calls keep working, which hides the problem until the first delegated call.

5. The Agent 365 CLI creates a client secret. Convenient for getting started; contrary to the reason for this pattern. Delete it once the federated credential works, and remember the CLI printed it.

6. CLI-built blueprints use access_agent_as_user. Callers who copy a token command from the hand-built version ask for access_agent and get an invalid-scope error from Entra. Check the scope name on the blueprint’s Expose an API page before handing out instructions.

7. A blueprint is not a general-purpose app. It may get the exchange token for its own agent identities and not much else. Asking for an app-only token as the blueprint for an unrelated resource fails with AADSTS82001 (for example Bot Framework, if you try to put the same agent on a Teams channel), and a blueprint can’t get an exchange token for another blueprint’s agent identity (AADSTS7002134). Design for “the agent identity holds the permissions”, never the blueprint.

8. Version pins matter more on AgentCore. bedrock-agentcore 1.24.1 requires a newer boto3 than many LangChain stacks pin; resolve that first. Build arm64 images; on an x86 build machine use buildx with QEMU. If image pulls from public registries are throttled in CI, log in to the registry rather than retrying.

9. One tracer provider. AgentCore’s observability and Microsoft’s Agent 365 exporter both want the global OpenTelemetry provider. Install Microsoft’s first; otherwise the exporter silently gets nothing.

10. Return claims, not tokens, when debugging. A diagnostic mode that decodes and returns selected claims for each hop (and AADSTS codes on failure) found every problem above in minutes, without a token ever leaving the container.

11. Governance didn’t change, and that’s the point. Conditional Access for agents blocked the unapproved agent identity with the same AADSTS53003 it returns anywhere else; sign-in logs showed the same agent types; Agent 365 got the same spans. Where the exchange runs is an implementation detail for Entra.

Common problems

SymptomCauseFix
Every call: Claim 'iss' value mismatchv1 discovery URLUse .../v2.0/.well-known/openid-configuration
401/403 from AgentCore, container never invokedNo or invalid token; audience not in allowed_audience; allowed_clients set (Entra tokens have no client_id claim)Check the caller’s aud and iss; remove allowed_clients
SessionDurationEscalationExceptionAWS token lifetime longer than the runtime sessionDurationSeconds=300
AADSTS70021 at step 1Issuer or subject differs from the federated credential (case, renamed role)Compare the AWS token’s iss/sub with the credential
AADSTS50013 at step 2bCaller token’s audience isn’t the blueprintRequest the token for api://<blueprint-app-id>/<scope>
On-behalf-of fails: no user tokenAuthorization not in the header allowlistrequest_header_allowlist = ["Authorization"]
.NET 401 on a valid tokenAzureAd:Audience set to api://...Remove it
AADSTS53003Conditional Access for agents blocked the agent identityIntended for unapproved agents; set the approval attribute for approved ones
AADSTS82001Asking for an app-only token as the blueprintRequest tokens as the agent identity (with T1)
Telemetry token issued but no spans arriveTwo tracer providers, or telemetry set up after LangChain loadedImport telemetry first; one provider

Sidecar or no sidecar?

ChooseWhen
Sidecar (ECS, EKS, any host you control)You can run more than one container; you want Microsoft to own the protocol code in every language; several agents share the same pattern.
In-process, .NETThe host runs one container (AgentCore Runtime, Lambda-style hosts) and the agent is .NET: Microsoft.Identity.Web does the protocol, you supply the AWS token.
In-process, Python (hand-written)The host runs one container and the agent must be Python. It works, but you own about 60 lines of security-critical protocol code; review it, test it with the claim checks above, and revisit when a supported library covers it.

Scaling to many agents

Everything above provisions one agent. The pattern scales to hundreds better than a client-secret approach, because there are no secrets to mint, store or rotate per agent. The work is in not creating a full per-agent copy of everything. Three levers do most of it.

One shared execution role, one blueprint, many agent identities — so you need a single federated credential. A blueprint can parent hundreds of agent identities, and the federated credential (step 1.3) trusts the execution role ARN, not the agent. If agents share an AgentCore execution role, one blueprint with one federated credential covers all of them, and fmi_path selects the agent identity at token time. That sidesteps the 20-federated-credentials-per-application limit entirely; it only bites if you try to trust many roles under one application. The trade-off, as in step 1.2: a shared blueprint is a shared “who may call” boundary and a shared exposed scope, so group agents by caller-authorization boundary rather than minting a blueprint each.

One container image, many runtimes. The code reads AGENT_IDENTITY_ID, AGENT_BLUEPRINT_ID, ORDERS_SCOPE and the rest from environment variables (step 3.1), so you build one arm64 image and deploy it as many AgentCore runtimes, each with its own env. No per-agent image build; a code change is one rebuild rolled across runtimes.

A declarative manifest reconciled in CI/CD. Keep a desired-state inventory of agents (name, sponsor, scope, caller group, image tag) and a parameterized Terraform or Bicep module that iterates over it: create or reference the blueprint, create the agent identity and registry entry, apply the grants (API role, OtelWrite, the Conditional Access approval attribute), create or update the runtime. The Graph calls are idempotent, so adding an agent is a change to the manifest. GitOps for agents.

The details that matter once there are hundreds:

  • Split the privilege. The provisioning pipeline creates objects, but keep the high-privilege governance grants (AppRoleAssignment.ReadWrite.All, Conditional Access) behind a controlled admin identity or an approval gate. Don’t give the bulk pipeline tenant-wide grant powers.
  • Govern with groups, not per-agent assignments. Caller authorization through security groups reused across agents; the Conditional Access approval attribute set per agent identity by the pipeline; scheduled access reviews on the groups.
  • Expect throttling and eventual consistency. Batch Graph calls and retry with backoff; the create-then-use ordering that needed a retry for one agent (Request_ResourceNotFound) needs it systematically at scale.
  • Inventory and drift. Hundreds of non-human and agent identities need continuous inventory and right-sizing, not just provisioning. The pipeline creates them; something has to watch which scope and reach each one holds, and which have drifted. Treat the fleet as a governed population, not a pile of one-offs.
  • Watch the quotas: 20 federated credentials per application (mitigated by the shared-role design above), Entra object limits, and AgentCore runtime and region quotas.

The short version: a shared execution role and blueprint with many agent identities (one federated credential), one parameterized image across many runtimes, and a declarative manifest reconciled by Terraform in CI/CD — with the governance grants gated behind an administrator.

What this gives you

  • An AgentCore agent with its own Entra agent identity, sponsor and owner, in the Agent 365 registry.
  • No secret anywhere (once the CLI’s is deleted): AWS signs a five-minute token about the execution role, Entra trusts it for one role and one audience.
  • Callers rejected before the container runs, by AgentCore, using Entra’s own keys.
  • The agent can act for the user (the user’s policies and permissions apply) or as itself (Conditional Access for agents applies), and every downstream service can tell which.
  • The same audit trail in Purview, Defender and the Microsoft 365 admin center as an agent hosted on Azure or ECS.

No sidecar, no token file, no second container. The only AWS-specific code is a call to STS that runs whenever Entra needs a fresh assertion.

Discussion

Comments are powered by Giscus / GitHub Discussions. They appear here once configured — see Configure Giscus in the project README and update GISCUS in src/consts.ts.