Microsoft Entra ID
Developer

Secure a web API with Microsoft Entra ID

In brief

The article now covers Microsoft Entra ID web API security, recommending supported token-validation middleware and documenting issuer, audience, signing-key, scope, and application-role configuration, with an ASP.NET Core example.

What Entra admins need to know

No administrator action is specified. API owners can use the revised guidance when configuring token validation and authorization.

This editorial summary was generated by AI from the documentation changes. Verify important details in the full Microsoft Learn article.

Documentation change

The comparison below shows only the changed extract. Use the full-page view for complete context.

Validate agent identitySecure a web API with Microsoft Entra ID

A downstream API must validate every access token before it trusts the Agent ID, user, or permissions represented by the token. Use a supported authentication middleware or token-validation library instead of parsing tokens in a downstream API

When an AI agent calls your API through the Microsoft Entra ID Auth SDK (sidecar), the request includes a Bearer token. Your API validates this token to confirm the request comes from an authenticated agent with the correct permissions. If validation fails, your API returns HTTP 401 with a reason.application code.

This article explainscovers Microsoft identity platform v2.0 access tokens.

The API registration must expose the delegated scope or application role that each endpoint requires, and the calling client or agent must have the corresponding grant. For an assembled local delegated test, follow Call a custom API as a user. For app-only caller setup and consent, follow Call a custom API as an agent.

Configure token validation

Configure the API with:

  • The Microsoft Entra tenant or accepted issuer set.
  • The API's Application ID URI or client ID as the expected audience.
  • Microsoft identity platform signing-key discovery.
  • The delegated scopes or application roles required by each operation.

For ASP.NET Core, use Microsoft.Identity.Web. For other frameworks, use a Microsoft-supported JWT validation checkslibrary.

For complete registration and shows howframework guidance, see Configure protected web API apps.

Configure an ASP.NET Core API

Install Microsoft.Identity.Web:

dotnet add package Microsoft.Identity.Web

Configure the tenant and API registration:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "<tenant-id>",
    "ClientId": "<downstream-api-client-id>"
  }
}

Register token validation and protect delegated and app-only endpoints:

using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMicrosoftIdentityWebApiAuthentication(
    builder.Configuration);

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy(
        "AgentApplication",
        policy => policy.RequireRole("Agent.Access"));
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/data-for-user", (HttpContext context) =>
{
    context.VerifyUserHasAnyAcceptedScope("access_as_user");
    return Results.Ok();
})
.RequireAuthorization();

app.MapGet("/data-for-agent", () => Results.Ok())
    .RequireAuthorization("AgentApplication");

app.Run();

Replace access_as_user with the delegated scope exposed by the API. Replace Agent.Access with the application role assigned to configurethe Agent ID.

AddMicrosoftIdentityWebApiAuthentication validates the token signature, issuer, audience, and runlifetime. VerifyUserHasAnyAcceptedScope enforces the delegated scp claim. RequireRole enforces the application permission in the roles claim.

For more complete authorization patterns, see Verify scopes and app roles in a protected web API.

Test each endpoint with a token issued for this downstream API, not the agent's inbound token. With the required scope or role, the sample weatherreturns 200 OK. Without a token or with the wrong audience, expect 401. With an otherwise valid token for this API that validates agent identitylacks the required scope or role, expect rejection. Use the linked walkthroughs for token acquisition; don't return or log tokens end-to-end.to inspect them.

PrerequisitesValidate the token

    Reject the request unless all of these checks succeed:

    1. Docker DesktopSignature: (macOS / Windows) or Docker Engine (Linux).
    2. A The token is signed by a trusted Microsoft Entra tenant with an agent identity blueprint and an agent identity. For setup steps, see Create an agent blueprint and Create and delete agent identities.signing key.
    3. An agent identityIssuer: The iss claim matches an issuer accepted by the API.
    4. Audience: The aud claim identifies this API.
    5. Lifetime: The token is within its valid time window.
    6. Tenant: The tid claim is allowed by the API's tenant policy.
    7. Client: The authorized-party claim identifies an allowed client or blueprint where the API restricts callers.
    8. Agent identity: Agent-specific claims, including the Agent ID relationship claims expected by the scenario, are present and valid.
    9. Permission: Delegated requests contain the required scp value; app-only requests contain the required roles value.

    Don't authorize a request based only on the presence of an Agent ID claim. Apply the same issuer, audience, lifetime, and permission checks used for testing. You can get one from the sidecar local development sample or from the scripts in the Microsoft Entra Agent ID samples repository.

other Microsoft Entra access tokens.

Token validation checksDistinguish access types

Your downstream API should perform four checks on every incoming agent identity token:

CheckAccess type What it verifiesUser context DetailsPermission claimAPI authorization
SignatureAgent acting as itself The token isn't tampered with.Noneroles Verify the RS256 signature against the JSON Web Key Set (JWKS) at https://login.microsoftonline.com/<tenant>/discovery/v2.0/keys.required application role and Agent ID.
IssuerAgent acting for a signed-in user Microsoft Entra ID issuedSigned-in userscpVerify the token.The iss claim matches https://sts.windows.net/<tenant>/ or https://login.microsoftonline.com/<tenant>/v2.0.scope, user authorization, and Agent ID.
AudienceAgent acting as its user account The token is intended for your API.Agent's user account The aud claim matches your API's expected audience value.
Agent identity markerThe token was issued to an agent, not a regular app.The xms_par_app_azp claim is present in agent identity tokens and absent in standard app-only tokens. This claim identifies the blueprint that created the agent.

When all four checks pass, your API can trust and process the request.

How the sample weather API works

The Microsoft Entra Agent ID samples repository includes a sample weather API that demonstrates these validation checks. The sample API is a minimal Flask app that acts as the downstream API your agent calls. It validates incoming agent identity tokens and returns real weather data from Open-Meteo.

Both the local development (Ollama) and AWS (Bedrock) sidecar samples call the same weather API container. The sample consists of three files:

  • app.py: Flask app with route handlers, token validation logic, and Open-Meteo client.
  • Dockerfile: Uses python:3.13-slim as the base image. Runs gunicorn app:app on port 8080.
  • requirements.txt: Dependencies: flask, pyjwt[crypto], cryptography, requests, gunicorn.

The API exposes two endpoints:

  • GET /weather?city=<name>: Validates the Authorization: Bearer <token> header and returns weather data for the specified city.
  • GET /healthz: Returns a health status without requiring token validation.

The following diagram shows how tokens flow from the agent through the sidecar to the weather API. The agent never contacts Microsoft Entra ID directly. Instead, the sidecar acquires a token (TR) on behalf of the agent identity, and the agent passes that token to the weather API in the Authorization: Bearer header.

:::image type="content" source="media/how-to-validate-agent-tokens-downstream-api/agent-token-flow-to-downstream-api.png" alt-text="Diagram showing the agent caller sending a Bearer token to the weather API, which verifies the token and calls Open-Meteo." lightbox="media/how-to-validate-agent-tokens-downstream-api/agent-token-flow-to-downstream-api.png":::

The agent identity token, TR, is issued by Microsoft Entra ID through the sidecar. It contains the claims your API validates, including the xms_par_app_azp agent identity marker. For a detailed breakdown of all tokens in the flow, see Run the sidecar for local development.

Token validation libraries differ across ecosystems (Python, Node.js, .NET). This sample uses PyJWT with the cryptography backend for RS256 signature verification. When you build your own downstream API, choose the equivalent JWT validation library for your technology stack.

Configure the sample weather API

The sample weather API accepts the following environment variables:

VariableRequiredDefaultPurpose
TENANT_IDscp Yes—Your Microsoft Entra tenant ID, used to buildVerify the JWKS URLscope, account authorization, and verify the issuer claim.
EXPECTED_AUDIENCENohttps://graph.microsoft.comThe expected aud claim value. Defaults to Microsoft Graph so that the same agent tokens work for local testing.
PORTNo8080The HTTP port the API listens on.Agent ID relationship.

Run the sample weather APIReturn authorization errors

To run the weather API as a standalone container and test token validation:

  1. Clone the repository and navigate to the weather API directory:

    git clone https://github.com/microsoft/entra-agentid-samples.git
    cd entra-agentid-samples/sidecar/weather-api
    
  2. Build and run the container:

    docker build -t weather-api:local .
    docker run --rm -p 8080:8080 \
      -e TENANT_ID=<your-tenant-id> \
      -e EXPECTED_AUDIENCE=https://graph.microsoft.com \
      weather-api:local
    
  3. Send a request with an agent identity token:

    curl -H "Authorization: Bearer $TOKEN" \
         "http://localhost:8080/weather?city=Dallas"
    

The API returns a JSON response that includes both the weather data and the token validation results:

{
  "city": "Dallas",
  "temperature": 61,
  "temperature_unit": "F",
  "condition": "Overcast",
  "humidity": 93,
  "wind_speed": 8,
  "is_agent_identity": true,
  "agent_app_id": "<agent-app-id from xms_par_app_azp>",
  "validated_by": "Agent Identity Token",
  "data_source": "Open-Meteo API (Real-time)"
}

The is_agent_identity, agent_app_id, and validated_by fields confirm token validation:

  • Return is_agent_identity: Set to true401 Unauthorized when the xms_par_app_azp claimtoken is present, which confirms the token was issued to an agent identity rather than a standard app registration.missing or invalid.
  • Return agent_app_id: The value of the xms_par_app_azp claim, which identifies the blueprint application that created the agent identity.
  • validated_by: The validation method applied to the token. Displays Agent Identity Token403 Forbidden when the agent markertoken is valid but lacks the required permission or resource access.

Don't include tokens or sensitive claim is present.values in logs.

Related content

Daily Entra.News

Get daily email updates

Get a concise summary of the latest Microsoft Entra updates delivered straight to your inbox.

Loading the secure signup form…