Microsoft Entra Agent ID
Developer

Call a custom API as an agent with ASP.NET Core

In brief

The guide now covers configuring an ASP.NET Core agent to obtain an app-only token and call a protected custom API, including credential setup, permission grants, and validation. It also clarifies that user access to invoke the agent is separate from the agent’s downstream API permissions.

What Entra admins need to know

Administrators may need to grant the downstream application permission and support the required agent and API role assignments.

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.

Call a custom APIs fromAPI as an agent using .NETwith ASP.NET Core

There are multiple ways to callUse app-only access when your cloud agent calls a custom APIs fromAPI with its own permissions, not the signed-in user's access. In this walkthrough, an agent. Depending on your scenario, you can use either IDownstreamApi, MicrosoftIdentityMessageHandler, or IAuthorizationHeaderProvider. This guide explainsauthorized user triggers the different approachesagent, and Microsoft.Identity.Web gets an app-only token for calling your own protected APIs all the three ways.downstream call.

[!INCLUDE Common call API content]

Decide which approach to use based on your scenario

The following table helps you decide which approach to use. For most scenarios, we recommend using IDownstreamApi.

ApproachComplexityFlexibilityUse Case
IDownstreamApiLowMediumStandard REST APIs with configuration
MicrosoftIdentityMessageHandlerMediumHighHttpClient with Direct Injection (DI)You'll configure the credential, grant access, and composable pipeline
IAuthorizationHeaderProviderHighVery HighComplete control over HTTP requests

Use IDownstreamApi

IDownstreamApi is the preferred way to callverify a protected API amongresponse. The user's permission to invoke the three options. Itagent and the agent's highly configurablepermission to call the downstream API are separate checks.

Prerequisites

  • An existing ASP.NET Core web API project and requires minimal code changes. Itthe .NET SDK for its target framework. The examples were tested with .NET 10 and Microsoft.Identity.Web 4.17.0; these are tested versions, not minimum supported versions.
  • Completion of Create an identity for your agent, including tenant enablement, administrator approvals, and the recorded client and object IDs.
  • A credential registered on the blueprint: a certificate for local testing, or a managed identity federated credential for an Azure host.
  • A custom API that exposes an application permission (app role), plus its application ID URI and HTTPS endpoint. The API must validate access tokens and enforce that role.
  • An administrator to grant the downstream application permission. For standard tenant-wide consent to a custom API, Cloud Application Administrator, Application Administrator, or AI Administrator can grant consent. Microsoft Graph application permissions instead require Privileged Role Administrator. Confirm the applicable role for this preview with your Microsoft representative. See Grant tenant-wide admin consent.
  • An authorized Microsoft Graph management client with Application.Read.All to verify the assignment. For delegated access, the signed-in user also offers automatic token acquisition.needs a supported role, such as Directory Readers. This read permission doesn't grant runtime access.
  • A caller configured through Authenticate users to the agent API, with Agent.User configured, verified, and assigned through Control access to agents. Complete both role-definition steps in that procedure. The sample retains RequireRole("Agent.User"); downstream consent doesn't authorize the caller.

Install the packages

If you don't have an existing project, create one with dotnet new webapi --framework net10.0 --name AgentApi, then run cd AgentApi. Keep your existing target framework when adding this guidance to an existing project.

Use IDownstreamApi when you needRun the following listed items:

  • You're calling standard REST APIs
  • You want a configuration-driven approach
  • You need automatic serialization/deserialization
  • You want to write minimal code

Use MicrosoftIdentityMessageHandler

MicrosoftIdentityMessageHandlercommand from the Microsoft.Identity.Web.TokenAcquisition package is a delegating handler that adds authentication to HttpClient requests. Use this when you need full HttpClient functionality with automatic token acquisition.

The Microsoft.Identity.Web.TokenAcquisition package is already referenced by Microsoft.Identity.Web.AgentIdentities.

Use MicrosoftIdentityMessageHandler when you need the following listed items:

  • You need fine-grained control over HTTP requests
  • You want to compose multiple message handlers
  • You're integrating with existing HttpClient-based code
  • You need access to raw HttpResponseMessage

Use IAuthorizationHeaderProvider

IAuthorizationHeaderProvider from Microsoft.Identity.Web gives you direct access to authorization headers for complete control over HTTP requests. This means you can customize the authentication process to fitdirectory containing your needs, including adding or modifying headers as necessary. This method also allows you to use custom HTTP libraries to makeweb API calls.

Use IAuthorizationHeaderProvider when you need the following listed items:

  • You need complete control over HTTP request construction
  • You're integrating with nonstandard HTTP APIs
  • You need to use HttpClient without DI
  • You're building custom HTTP abstractions

Call your API

After determining what works for you, proceed to call your custom web API.

[!INCLUDE Dont use secrets]

Use IDownstreamApi

  1. Install the required NuGet package:s project file:

    dotnet add package Microsoft.Identity.Web.DownstreamApi
    dotnet add package Microsoft.Identity.Web.AgentIdentitiesWeb --version 4.17.0
    
  2. Configure tokenthe blueprint credential options

    Use the configuration for where you run the API. Configure one credential source, not both.

    Local workstation

    Configure a local development credential

    In the agent project's appsettings.json, set AzureAd:Instance to https://login.microsoftonline.com/, AzureAd:TenantId to your tenant ID, and your APIsAzureAd:ClientId to the client ID recorded during setup.

    Use the certificate registered during setup. You need the corresponding PFX containing the private key, not just the public certificate uploaded to Microsoft Graph.

    In appsettings.Development.json, use this ClientCredentials array. Don't append a managed identity credential or commit the PFX file.

    {
      "AzureAd": {
        "ClientCredentials": [
          {
            "SourceType": "Path",
            "CertificateDiskPath": "<absolute-path-to-local-pfx>"
          }
        ]
      }
    }
    

    In the PowerShell terminal that starts the app, set $env:ASPNETCORE_ENVIRONMENT = "Development" and set $env:AzureAd__ClientCredentials__0__CertificatePassword = Read-Host "PFX password" -MaskInput. Use PowerShell 7 for -MaskInput. The environment variable supplies the password without placing it in the JSON file or shell history. Clear it with Remove-Item Env:\AzureAd__ClientCredentials__0__CertificatePassword after stopping the app. Don't use this local file configuration in production.

    Azure host

    Use this configuration on an Azure host with the specified user-assigned managed identity assigned and its federated credential configured on the blueprint. It doesn't provide a workstation credential.

    Set ClientId to the client ID recorded during setup in appsettings.json.:

    {
      "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "TenantId": "your-<tenant-id>",
        "ClientId": "your-blueprint-<agent-client-id>",
        "ClientCredentials": [
          {
            "SourceType": "ClientSecretSignedAssertionFromManagedIdentity",
            "ClientSecretManagedIdentityClientId": "your-<managed-identity-client-secretid>"
          }
        ]
      },
      "DownstreamApis": {
        "MyApi": {
          "BaseUrl": "https://api.example.com",
          "Scopes": ["api://my-api-client-id/read", "api://my-api-client-id/write"],
          "RelativePath": "/api/v1",
          "RequestAppToken": false
        }
      }
    }
    

    [!INCLUDE Dont use secrets]

    Grant application permissions

    Declare the API's app role in the blueprint's requiredResourceAccess, as described in the creation procedure. Declaring a permission doesn't grant it.

    Use the custom API's configured application ID URI followed by /.default in both the consent request and the token request. The default URI format is api://<custom-api-client-id>, but a custom URI must be used instead if the API defines one.

    1. Have the administrator open the following URL in a browser, sign in, and review the requested permissions. Replace the placeholders, URL-encode the query parameter values, and join the lines into one URL. Use a web redirect URI registered on the blueprint, even when the agent only runs unattended. Generate a unique state value and retain it to validate the callback.

      GET https://login.microsoftonline.com/<tenant-id>/v2.0/adminconsent
          ?client_id=<agent-client-id>
          &scope=<custom-api-application-id-uri>/.default
          &redirect_uri=<registered-web-redirect-uri>
          &state=<state>
      
    2. Match the returned state to the value you sent. Confirm that admin_consent=True is present and no error parameter is returned. Error callbacks also include admin_consent=True. Check the expected tenant, but don't use the callback's tenant value to authenticate or authorize a caller. For the response formats, see Admin consent on the Microsoft identity platform.

    3. Open Microsoft Graph Explorer and sign in to the same tenant with the authorized management account. Use Modify permissions to request Application.Read.All, and have an authorized administrator grant consent if required. Select GET and v1.0, then run the following request. Graph Explorer supplies its management access token; don't use the agent's downstream token.

      GET https://graph.microsoft.com/v1.0/servicePrincipals/<agent-identity-object-id>/appRoleAssignments
      

      Use the agent identity's id recorded during creation for <agent-identity-object-id>, not its shared OAuth client ID or the blueprint's object ID. Follow any @odata.nextLink values. Confirm that principalId is the agent identity's object ID, resourceId is the custom API's service principal object ID, and appRoleId is the intended role. For the required read permissions and delegated-user roles, see List appRoleAssignments.

    Allow time for a new assignment to become visible. If it remains missing, confirm the approved permission and tenant before requesting a token.

    Configure your services to addASP.NET Core

    In Program.cs, register Microsoft.Identity.Web, an HTTP client, and the inbound AgentUser authorization policy. This path uses ordinary confidential-client token acquisition, without AddAgentIdentities or WithAgentIdentity. The incoming caller's token is for the agent API; the downstream API support:app-only token is for the custom API.

    using System.Net.Http.Headers;
    using Microsoft.AspNetCore.Authentication.OpenIdConnect;Identity.Abstractions;
    using Microsoft.Identity.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add authentication
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Services
        .AddMicrosoftIdentityWebApiAuthentication(builder.Configuration.GetSection("AzureAd"))Configuration)
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddInMemoryTokenCaches();
    
    // Register downstream APIs
    builder.Services.AddDownstreamApis(AddHttpClient();
    builder.Configuration.GetSection(Services.AddAuthorization(options =>
    {
        options.AddPolicy(
            "DownstreamApisAgentUser",
            policy => policy.RequireRole("Agent.User"));
    // Add Agent Identities support
    builder.Services.AddAgentIdentities();
    
    builder.Services.AddControllersWithViews()});
    
    var app = builder.Build();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    // Map the custom API endpoint before app.MapControllers(Run();.
    app.Run();
    
  3. Call your protectedthe API using

    Use IDownstreamApiIAuthorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync. When callingPass the API,custom API's .default scope as a string. Replace <custom-api-application-id-uri> with the same URI you can specifyused for consent, and replace https://api.contoso.com/data with the agent identity or agent's user account identity usingAPI endpoint. The provider uses the configured client ID and credential directly.

    Insert the following endpoint at the comment in WithAgentIdentityProgram.cs, before app.Run(). The required using or WithAgentUserIdentity methods. IDownstreamApi automatically handles token acquisitiondirectives are already at the top of the file. The endpoint gets an app-only authorization header and attaches the access tokensends it to the request.

    • For WithAgentIdentity, you either call the API using an app only token (autonomous agent) or on-behalf of a user (interactive agent).custom API:

      using Microsoft.Identity.Abstractions;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc;
      
      [Authorize]
      public class ProductsController : Controller
      {
          private readonly IDownstreamApi _api;
      
          public ProductsController(IDownstreamApi api)
          {
              _api = api;
          }
      
          // GET request for app only token scenario for agent identity
          publicapp.MapGet("/custom-api", async Task<IActionResult> Index()
          {
      
              string agentIdentity = "<your-agent-identity>";
              var products = await _api.GetForAppAsync<List<Product>>(
          "MyApi",
                  "products",
                  options => options.WithAgentIdentity(agentIdentity));
      
              return View(products);
          }
      
          // GET request for on-behalf of user token scenario for agent identity
          public async Task<IActionResult> UserProducts()
          {
      
              string agentIdentity = "<your-agent-identity>";
              var products = await _api.GetForUserAsync<List<Product>>(
                  "MyApi",
                  "products",
                  options => options.WithAgentIdentity(agentIdentity));
      
              return View(products);
          }
      }
      
    • For WithAgentUserIdentity, you can specify either User Principal Name (UPN) or Object Identity (OID) to identify the agent's user account.

      using Microsoft.Identity.Abstractions;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc;
      
      [Authorize]
      public class ProductsController : Controller
      {
          private readonly IDownstreamApi _api;
      
          public ProductsController(IDownstreamApi api)
          {
              _api = api;
          }
      
          // GET request for agent's user account identity using UPN
          public async Task<IActionResult> Index()
          {
      
              string agentIdentity = "<your-agent-identity>";
              string userUpn = "[email protected]";
      
              var products = await _api.GetForUserAsync<List<Product>>(
                  "MyApi",
                  "products",
                  options => options.WithAgentUserIdentity(agentIdentity, userUpn));
              return View(products);
          }
      
          // GET request for agent's user account identity using OID
          public async Task<IActionResult> UserProducts()
          {
      
              string agentIdentity = "<your-agent-identity>";
              string userOid = "user-object-id";
      
              var products = await _api.GetForUserAsync<List<Product>>(
                  "MyApi",
                  "products",
                  options => options.WithAgentUserIdentity(agentIdentity, userOid));
      
              return View(products);
          }
      
      }
      

Use MicrosoftIdentityMessageHandler

  1. Install the required NuGet package:

    dotnet add package Microsoft.Identity.Web.AgentIdentities
    
  2. Configure your services to add authentication with agent identities and register HttpClient with MicrosoftIdentityMessageHandler:

    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.Identity.Web;
    using Microsoft.Identity.Abstractions;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddInMemoryTokenCaches();
    
    // Configure named HttpClient with authentication
    builder.Services.AddHttpClient("MyApiClient", clientIAuthorizationHeaderProvider authorizationHeaderProvider,
        IHttpClientFactory httpClientFactory) =>
    {
        client.BaseAddressstring authorizationHeader = new Uri(await authorizationHeaderProvider
            .CreateAuthorizationHeaderForAppAsync(
                "https:<custom-api-application-id-uri>//api.example.com.default");
    
        HttpClient client = httpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("Accept", "application/json")Authorization =
            AuthenticationHeaderValue.Parse(authorizationHeader);
    
        client.Timeout = TimeSpan.FromSeconds(30);
    })
    .AddHttpMessageHandler(sp =>
    {
        var authProvider = sp.GetRequiredService<IAuthorizationHeaderProvider>();
        return new MicrosoftIdentityMessageHandler(
            authProvider,
            new MicrosoftIdentityMessageHandlerOptions
            {
                Scopes = new[] { "api://my-api-client-id/read" },
            });
    });
    
    builder.Services.AddControllersWithViews();
    
    // Add Agent Identities support
    builder.Services.AddAgentIdentities();
    
    
    var app = builder.Build();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    
  3. Acquire token and call your protected API using the configured HttpClient. You can specify the agent identity or agent's user account using the WithAgentIdentity or WithAgentUserIdentity methods.

    • For WithAgentIdentity, you either call the API using an app only token (autonomous agent) or on-behalf of a user (interactive agent).

      To call the API using an app only token for the agent identity, set RequestAppToken to true.

      public class MyService
      {
          private readonly HttpClient _httpClient;
      
          public MyService(IHttpClientFactory httpClientFactory)
          {
              _httpClient = httpClientFactory.CreateClient("MyApiClient");
          }
      
          public async Task<string> CallApiWithAgentIdentity(string agentIdentity)
          {
              // Create request with agent identity authentication
              var request = new HttpRequestMessage(HttpMethod.Get, "/api/data")
                  .WithAuthenticationOptions(options =>
                  {
                      options.WithAgentIdentity(agentIdentity);
                      options.RequestAppToken = true;
                  });
      
              var response = await _httpClient.SendAsync(request);
              response.EnsureSuccessStatusCode();
              return await response.Content.ReadAsStringAsync();
          }
      }
      

      To call the API on-behalf of a user for the agent identity, don't set RequestAppToken or explicitly set it to false.

      public class MyService
      {
          private readonly HttpClient _httpClient;
      
          public MyService(IHttpClientFactory httpClientFactory)
          {
              _httpClient = httpClientFactory.CreateClient("MyApiClient");
          }
      
          public async Task<string> CallApiWithAgentIdentity(string agentIdentity)
          {
              // Create request with agent identity authentication
              var request = new HttpRequestMessage(HttpMethod.Get, "/api/data")
                  .WithAuthenticationOptions(options =>
                  {
                      options.WithAgentIdentity(agentIdentity);
                      options.RequestAppToken = false;
                  });
      
              var response = await _httpClient.SendAsync(request);
              response.EnsureSuccessStatusCode();
              return await response.Content.ReadAsStringAsync();
          }
      }
      
    • To use WithAgentUserIdentity, you can specify either UPN or OID to identify the agent's user account.

      // Create request with agent's user account identity authentication with UPN
      public async Task<string> CallApiWithAgentUserIdentityByUpn(string agentIdentity, string userUpn)
      {
      
          var request = new HttpRequestMessage(HttpMethod.Get, "/api/userdata")
              .WithAuthenticationOptions(options =>
              {
                  options.WithAgentUserIdentity(agentIdentity, userUpn);
                  options.Scopes.Add("https://myapi.domain.com/user.read");
              });
      
          var response = await _httpClient.SendAsync(request);
          response.EnsureSuccessStatusCode();
          return await response.Content.ReadAsStringAsync();
      }
      
      // Create request with agent's user account identity authentication with OID
      public async Task<string> CallApiWithAgentUserIdentityByOid(string agentIdentity, string userOid)
      {
      
          var request = new HttpRequestMessage(HttpMethod.Get, "/api/userdata")
              .WithAuthenticationOptions(options =>
              {
                  options.WithAgentUserIdentity(agentIdentity, userOid);
                  options.Scopes.Add("https://myapi.domain.com/user.read");
              });
      
          var response = await _httpClient.SendAsync(request);
          response.EnsureSuccessStatusCode();
          return await response.Content.ReadAsStringAsync();
      }
      

Use IAuthorizationHeaderProvider

  1. Install the required NuGet package:

    dotnet add package Microsoft.Identity.Web.AgentIdentities
    
  2. Configure your services to add authentication with agent identities:

    using Microsoft.AspNetCore.Authorization;
    using Microsoft.Identity.Abstractions;
    using Microsoft.Identity.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // With Microsoft.Identity.Web
    builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration)
        .EnableTokenAcquisitionToCallDownstreamApi();
    
    builder.Services.AddAgentIdentities();
    
    var app = builder.Build();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.Run();
    
    • Configure auth credentials in appsettings.json
    {
      "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "TenantId": "your-tenant-id",
        "ClientId": "your-blueprint-id",
        "ClientCredentials": [
          {
            "SourceType": "ClientSecret",
            "ClientSecret": "your-client-secret"
          }
        ]
      }
    }
    
  3. Acquire and extract access token then call the web API.

    • For WithAgentIdentity, you either call the API using an app only token (autonomous agent) or on-behalf of a user (interactive agent).

      • For app only token scenario, use CreateAuthorizationHeaderForAppAsync method.
      • For the on-behalf-of (OBO) token scenario, use CreateAuthorizationHeaderForUserAsync method
      using Microsoft.Identity.Abstractions;
      
      [Authorize]
      public class CustomApiController : Controller
      {
          private readonly IAuthorizationHeaderProvider _headerProvider;
      
          public CustomApiController(IAuthorizationHeaderProvider headerProvider)
          {
              _headerProvider = headerProvider;
          }
      
          // App only token scenario for agent identity
          public async Task<IActionResult> GetBackgroundData()
          {
              // Configure options for the agent identity
              string agentIdentity = "agent-identity-guid";
              var options = new AuthorizationHeaderProviderOptions()
                  .WithAgentIdentity(agentIdentity);
      
              // Acquire an access token for the agent identity
              var authHeader = await _headerProvider.CreateAuthorizationHeaderForAppAsync(
                  scopes: new[] { "api://my-api/.default" }, options: options);
      
              // Call the protected API
              using var client = new HttpClient();
              client.DefaultRequestHeaders.Add("Authorization", authHeader);
      
              varHttpResponseMessage response =
              await client.GetAsync("https://api.example.contoso.com/backgrounddata");
          var data = await response.Content.ReadFromJsonAsync<BackgroundData>(EnsureSuccessStatusCode();
      
          return Ok(data)Results.Content(
              await response.Content.ReadAsStringAsync(),
              response.Content.Headers.ContentType?.ToString());
      }
      
          // On-behalf})
      .RequireAuthorization("AgentUser");
      

      The returned authorization header includes the Bearer scheme. Don't return tokens or authorization headers from a production endpoint.

      The sample requires an authenticated caller with the Agent.User role. Configure that assignment through the agent's inbound access policy before allowing the caller to trigger an app-only operation.

      Request only the application permissions required by the endpoint. For guidance on defining and granting app roles, see application roles.

      Verify API access

      A successful token response doesn't establish authorization at the API.

      1. Run the project from its project directory in an environment where the configured blueprint credential is available. The managed identity configuration requires an Azure host with the specified managed identity and federation configured; it doesn't provide a local workstation credential.

        dotnet run --urls https://localhost:5001
        

        For a workstation, complete Configure a local development credential first. Trust the ASP.NET Core development certificate if necessary with dotnet dev-certs https --trust; this can require interactive confirmation. Don't disable certificate validation. For an unattended local smoke test of userthe unauthenticated 401 response only, you can instead start with dotnet run --urls http://localhost:5001 and call that HTTP URL without a token. Don't send access tokens over HTTP.

      2. Use the upstream client from Authenticate users to the agent API to obtain an access token scenario for agent identity public async Task<IActionResult> GetUserData() { // Configure options for the agent identity string agentIdentityAPI, with the required delegated scope and Agent.User role. Request a new token after changing assignments. Make it available as the AGENT_API_ACCESS_TOKEN environment variable in your test shell without recording it in source control or shell history. Don't substitute an ID token, Graph management token, or downstream custom API token.

      3. In a separate PowerShell terminal, call the agent endpoint:

        $response = Invoke-WebRequest `
            -Uri "agent-identity-guidhttps://localhost:5001/custom-api";
                var options `
            -Headers @{ Authorization = new AuthorizationHeaderProviderOptions()
                    .WithAgentIdentity(agentIdentity);
        
                // Acquire"Bearer $env:AGENT_API_ACCESS_TOKEN" }
        $response.StatusCode
        $response.Content
        

        For an accessAPI endpoint that returns 200 OK, expect 200 and its response body. The agent calls the custom API as itself, not as the inbound user. A downstream non-success status causes EnsureSuccessStatusCode to fail; this sample doesn't translate downstream errors into matching inbound status codes.

      4. Repeat the request without an authorization header: expect 401 Unauthorized from the agent. With an otherwise valid agent API token forthat lacks Agent.User, expect 403 Forbidden if the tenant issues that token. When assignment is required, the tenant might reject token issuance first.

      5. At the downstream API, confirm signature, issuer, audience, lifetime, and the required app role are validated. Compare the validated token's oid with the agent identity var authHeader = await _headerProvider.CreateAuthorizationHeaderForUserAsync( scopes: new[] { "api://my-api/.default" }, options: options); // Callobject ID, not the protected API using var client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", authHeader); varblueprint object ID, and check its roles claim. See Validate Agent ID tokens in a downstream API. A successful token response = await client.GetAsync("https://api.example.com/background"); var data = await response.Content.ReadFromJsonAsync<BackgroundData>(); return Ok(data); } } alone doesn't prove these checks.

      6. For WithAgentUserIdentity, you callTest the downstream API on behalf's rejection of a usertoken without its required role, using their UPNa separate test identity or OID.

        using Microsoft.Identity.Abstractions;
        
        [Authorize]
        public class CustomApiController : Controller
        {
            private readonly IAuthorizationHeaderProvider _headerProvider;
        
            public CustomApiController(IAuthorizationHeaderProvider headerProvider)
            {
                _headerProvider = headerProvider;
            }
        
            // App only token scenario for agent identity
            public async Task<IActionResult> GetBackgroundData()
            {
                // Configure options forfixture rather than removing production grants. Expect rejection at that API; don't infer its status from the agent identity
                string agentIdentity = "agent-identity-guid";
                string userUpn = "[email protected]";
        
                var options = new AuthorizationHeaderProviderOptions()
                    .WithAgentUserIdentity(agentIdentity, userUpn);
        
                // Create a ClaimsPrincipal to enable token caching
                ClaimsPrincipal user = new ClaimsPrincipal();
        
                // Acquire an access token for the agent identity
                var authHeader = await _headerProvider.CreateAuthorizationHeaderForAppAsync(
                    scopes: new[] { "api://my-api/.default" }, options: options, user: user);
        
                // Call the protected API
                using var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", authHeader);
        
                var response = await client.GetAsync("https://api.example.com/background");
                var data = await's exception response.Content.ReadFromJsonAsync<BackgroundData>();
        
                return Ok(data);
            }
        
            // On-behalf of user token scenario for agent identity
            public async Task<IActionResult> GetUserData()
            {
                // Configure options for the agent identity
                string agentIdentity = "agent-identity-guid";
                string userUpn = "[email protected]";
        
                var options = new AuthorizationHeaderProviderOptions()
                    .WithAgentUserIdentity(agentIdentity, userUpn);
        
                // Create a ClaimsPrincipal to enable token caching
                ClaimsPrincipal user = new ClaimsPrincipal();
        
                // Acquire an access token for the agent identity
                var authHeader = await _headerProvider.CreateAuthorizationHeaderForAppAsync(
                    scopes: new[] { "api://my-api/.default" }, options: options, user: user);
        
                // Call the protected API
                using var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", authHeader);
        
                var response = await client.GetAsync("https://api.example.com/background");
                var data = await response.Content.ReadFromJsonAsync<BackgroundData>();
        
                return Ok(data);
            }
        }
        


Don't log access tokens, certificate assertions, or private keys. Record correlation IDs and request times when troubleshooting.

Next step

Validate Agent ID tokens in a downstream API

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…