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.
| |||
| |||
|
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.Allto verify the assignment. For delegated access, the signed-in user alsooffers 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.Userconfigured, verified, and assigned through Control access to agents. Complete both role-definition steps in that procedure. The sample retainsRequireRole("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 APIsYou want a configuration-driven approachYou need automatic serialization/deserializationYou want to write minimal code
Use MicrosoftIdentityMessageHandler
command from the MicrosoftIdentityMessageHandlerMicrosoft.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 requestsYou want to compose multiple message handlersYou're integrating with existing HttpClient-based codeYou 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 constructionYou're integrating with nonstandard HTTP APIsYou need to use HttpClient without DIYou'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
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.0Configure
tokenthe blueprint credentialoptionsUse 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, setAzureAd:Instancetohttps://login.microsoftonline.com/,AzureAd:TenantIdto your tenant ID, andyour APIsAzureAd:ClientIdto 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 thisClientCredentialsarray. 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 withRemove-Item Env:\AzureAd__ClientCredentials__0__CertificatePasswordafter 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
ClientIdto the client ID recorded during setup inappsettings.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
/.defaultin both the consent request and the token request. The default URI format isapi://<custom-api-client-id>, but a custom URI must be used instead if the API defines one.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
webredirect URI registered on the blueprint, even when the agent only runs unattended. Generate a uniquestatevalue 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>Match the returned
stateto the value you sent. Confirm thatadmin_consent=Trueis present and noerrorparameter is returned. Error callbacks also includeadmin_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.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>/appRoleAssignmentsUse the agent identity's
idrecorded during creation for<agent-identity-object-id>, not its shared OAuth client ID or the blueprint's object ID. Follow any@odata.nextLinkvalues. Confirm thatprincipalIdis the agent identity's object ID,resourceIdis the custom API's service principal object ID, andappRoleIdis 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 CoreIn
Program.cs, register Microsoft.Identity.Web, an HTTP client, and the inboundAgentUserauthorization policy. This path uses ordinary confidential-client token acquisition, withoutAddAgentIdentitiesorWithAgentIdentity. The incoming caller's token is for the agent API; the downstreamAPI 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 authenticationbuilder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(Services .AddMicrosoftIdentityWebApiAuthentication(builder.Configuration.GetSection("AzureAd"))Configuration) .EnableTokenAcquisitionToCallDownstreamApi() .AddInMemoryTokenCaches();// Register downstream APIsbuilder.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();Call
your protectedthe APIusingUse
.IDownstreamApiIAuthorizationHeaderProvider.CreateAuthorizationHeaderForAppAsyncWhen callingPass theAPI,custom API's.defaultscope as a string. Replace<custom-api-application-id-uri>with the same URI youcan specifyused for consent, and replacehttps://api.contoso.com/datawith theagent 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
, beforeWithAgentIdentityProgram.csapp.Run(). The requiredusingorWithAgentUserIdentitymethods.IDownstreamApiautomatically handles token acquisitiondirectives are already at the top of the file. The endpoint gets an app-only authorization header andattaches the access tokensends it to therequest.ForWithAgentIdentity, 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", asyncTask<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); } }ForWithAgentUserIdentity, 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
Install the required NuGet package:dotnet add package Microsoft.Identity.Web.AgentIdentitiesConfigure your services to add authentication with agent identities and register HttpClient withMicrosoftIdentityMessageHandler: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();Acquire token and call your protected APIusingthe configured HttpClient. You can specify the agent identity or agent's user account using theWithAgentIdentityorWithAgentUserIdentitymethods.ForWithAgentIdentity, 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, setRequestAppTokentotrue.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 setRequestAppTokenor explicitly set it tofalse.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 useWithAgentUserIdentity, 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
Install the required NuGet package:dotnet add package Microsoft.Identity.Web.AgentIdentitiesConfigure 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 inappsettings.json
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "TenantId": "your-tenant-id", "ClientId": "your-blueprint-id", "ClientCredentials": [ { "SourceType": "ClientSecret", "ClientSecret": "your-client-secret" } ] } }Acquire and extract access token then call the web API.ForWithAgentIdentity, 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, useCreateAuthorizationHeaderForAppAsyncmethod.For the on-behalf-of (OBO) token scenario, useCreateAuthorizationHeaderForUserAsyncmethod
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 = awaitresponse.Content.ReadFromJsonAsync<BackgroundData>(EnsureSuccessStatusCode(); returnOk(data)Results.Content( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentType?.ToString());} // On-behalf}) .RequireAuthorization("AgentUser");The returned authorization header includes the
Bearerscheme. Don't return tokens or authorization headers from a production endpoint.The sample requires an authenticated caller with the
Agent.Userrole. 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.
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:5001For 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 ofuserthe unauthenticated401response only, you can instead start withdotnet run --urls http://localhost:5001and call that HTTP URL without a token. Don't send access tokens over HTTP.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 optionsfor the agentidentity string agentIdentityAPI, with the required delegated scope andAgent.Userrole. Request a new token after changing assignments. Make it available as theAGENT_API_ACCESS_TOKENenvironment 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.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.ContentFor an
accessAPI endpoint that returns200 OK, expect200and its response body. The agent calls the custom API as itself, not as the inbound user. A downstream non-success status causesEnsureSuccessStatusCodeto fail; this sample doesn't translate downstream errors into matching inbound status codes.Repeat the request without an authorization header: expect
401 Unauthorizedfrom the agent. With an otherwise valid agent API tokenforthat lacksAgent.User, expect403 Forbiddenif the tenant issues that token. When assignment is required, the tenant might reject token issuance first.At the downstream API, confirm signature, issuer, audience, lifetime, and the required app role are validated. Compare the validated token's
oidwith the agent identityvar authHeader = await _headerProvider.CreateAuthorizationHeaderForUserAsync( scopes: new[] { "api://my-api/.default" }, options: options); // Callobject ID, not theprotected API using var client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", authHeader); varblueprint object ID, and check itsrolesclaim. 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.ForWithAgentUserIdentity, you callTest the downstream APIon behalf's rejection of ausertoken without its required role, usingtheir UPNa separate test identity orOID.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 agentidentity 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
@@ -1,574 +1,229 @@ ----title: Call custom APIs from an agent using .NET+title: Call a custom API as an agent with ASP.NET Core titleSuffix: Microsoft Entra Agent ID-description: Learn how to call custom protected APIs from an agent using different approaches including IDownstreamApi, MicrosoftIdentityMessageHandler, and IAuthorizationHeaderProvider.+description: Configure an ASP.NET Core agent to get an app-only token and call a custom API. ms.topic: how-to-ms.date: 11/04/2025-ms.reviewer: jmprieur-#Customer intent: As a developer building AI agents, I want to call custom protected APIs from my agent using agent identities so that the agent can securely access organization-specific services and resources.+ms.date: 11/06/2026+ms.reviewer: jmprieur, jomondi, dastrock+#Customer intent: As a developer building a cloud agent, I want to call my protected API as the agent so that unattended operations use the agent's application permissions.+ai-usage: ai-assisted+ms.custom: msecd-doc-authoring-1013 --- -# Call custom APIs from an agent using .NET+# Call a custom API as an agent with ASP.NET Core -There are multiple ways to call custom APIs from an agent. Depending on your scenario, you can use either `IDownstreamApi`, `MicrosoftIdentityMessageHandler`, or `IAuthorizationHeaderProvider`. This guide explains the different approaches for calling your own protected APIs all the three ways.+Use app-only access when your cloud agent calls a custom API with its own permissions, not the signed-in user's access. In this walkthrough, an authorized user triggers the agent, and Microsoft.Identity.Web gets an app-only token for the downstream call. -[!INCLUDE [Common call API content](./includes/call-api-common-dotnet.md)]+You'll configure the credential, grant access, and verify a protected API response. The user's permission to invoke the agent and the agent's permission to call the downstream API are separate checks. -## Decide which approach to use based on your scenario+## Prerequisites -The following table helps you decide which approach to use. For most scenarios, we recommend using `IDownstreamApi`. +- An existing ASP.NET Core web API project and the .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](create-single-instance-agent.md), 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](#grant-application-permissions). 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](~/identity/enterprise-apps/grant-admin-consent.md).+- An authorized Microsoft Graph management client with `Application.Read.All` to verify the assignment. For delegated access, the signed-in user also 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](aspnet-core-authenticate-users.md), with `Agent.User` configured, verified, and assigned through [Control access to agents](control-user-access-agents.md#define-app-roles). Complete both role-definition steps in that procedure. The sample retains `RequireRole("Agent.User")`; downstream consent doesn't authorize the caller. -| Approach | Complexity | Flexibility | Use Case |-|----------|------------|-------------|----------|-| `IDownstreamApi` | Low | Medium | Standard REST APIs with configuration |-| `MicrosoftIdentityMessageHandler` | Medium | High | HttpClient with Direct Injection (DI) and composable pipeline |-| `IAuthorizationHeaderProvider` | High | Very High | Complete control over HTTP requests |+## Install the packages -## [Use IDownstreamApi](#tab/idownstream)+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. -`IDownstreamApi` is the preferred way to call a protected API among the three options. It's highly configurable and requires minimal code changes. It also offers automatic token acquisition.+Run the following command from the directory containing your web API's project file: -Use `IDownstreamApi` when you need the following listed items:+```dotnetcli+dotnet add package Microsoft.Identity.Web --version 4.17.0+``` -- You're calling standard REST APIs-- You want a configuration-driven approach-- You need automatic serialization/deserialization-- You want to write minimal code+## Configure the blueprint credential -## [Use MicrosoftIdentityMessageHandler](#tab/messagehandler)+Use the configuration for where you run the API. Configure one credential source, not both. -`MicrosoftIdentityMessageHandler` 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.+# [Local workstation](#tab/local) -The *Microsoft.Identity.Web.TokenAcquisition* package is already referenced by *Microsoft.Identity.Web.AgentIdentities*.+### Configure a local development credential -Use `MicrosoftIdentityMessageHandler` when you need the following listed items:+In the agent project's `appsettings.json`, set `AzureAd:Instance` to `https://login.microsoftonline.com/`, `AzureAd:TenantId` to your tenant ID, and `AzureAd:ClientId` to the client ID recorded during setup. -- 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 the [certificate registered during setup](create-single-instance-agent.md#add-a-certificate-for-confidential-clients). You need the corresponding PFX containing the private key, not just the public certificate uploaded to Microsoft Graph. -## [Use IAuthorizationHeaderProvider](#tab/authheaderprovider)+In `appsettings.Development.json`, use this `ClientCredentials` array. Don't append a managed identity credential or commit the PFX file. -`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 fit your needs, including adding or modifying headers as necessary. This method also allows you to use custom HTTP libraries to make API calls.+```json+{+ "AzureAd": {+ "ClientCredentials": [+ {+ "SourceType": "Path",+ "CertificateDiskPath": "<absolute-path-to-local-pfx>"+ }+ ]+ }+}+``` -Use `IAuthorizationHeaderProvider` when you need the following listed items:+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. -- 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+# [Azure host](#tab/azure) ----+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`: -## Call your API+```json+{+ "AzureAd": {+ "Instance": "https://login.microsoftonline.com/",+ "TenantId": "<tenant-id>",+ "ClientId": "<agent-client-id>",+ "ClientCredentials": [+ {+ "SourceType": "SignedAssertionFromManagedIdentity",+ "ManagedIdentityClientId": "<managed-identity-client-id>"+ }+ ]+ }+}+``` -After determining what works for you, proceed to call your custom web API.+--- [!INCLUDE [Dont use secrets](./includes/do-not-use-secrets.md)] -## [Use IDownstreamApi](#tab/idownstream)+## Grant application permissions -1. Install the required NuGet package:+Declare the API's app role in the blueprint's `requiredResourceAccess`, as described in the creation procedure. Declaring a permission doesn't grant it. - ```bash- dotnet add package Microsoft.Identity.Web.DownstreamApi- dotnet add package Microsoft.Identity.Web.AgentIdentities- ```+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. Configure token credential options and your APIs in *appsettings.json*.-- ```json- {- "AzureAd": {- "Instance": "https://login.microsoftonline.com/",- "TenantId": "your-tenant-id",- "ClientId": "your-blueprint-id",- "ClientCredentials": [- {- "SourceType": "ClientSecret",- "ClientSecret": "your-client-secret"- }- ]- },- "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- }- }- }- ```+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. -1. Configure your services to add downstream API support:-- ```csharp- using Microsoft.AspNetCore.Authentication.OpenIdConnect;- using Microsoft.Identity.Web;- - var builder = WebApplication.CreateBuilder(args);- - // Add authentication- builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)- .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))- .EnableTokenAcquisitionToCallDownstreamApi()- .AddInMemoryTokenCaches();- - // Register downstream APIs- builder.Services.AddDownstreamApis(- builder.Configuration.GetSection("DownstreamApis"));-- // Add Agent Identities support- builder.Services.AddAgentIdentities();- - builder.Services.AddControllersWithViews();- - var app = builder.Build();- app.UseAuthentication();- app.UseAuthorization();- app.MapControllers();- app.Run();+ ```http+ 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> ``` -1. Call your protected API using `IDownstreamApi`. When calling the API, you can specify the agent identity or agent's user account identity using the `WithAgentIdentity` or `WithAgentUserIdentity` methods. `IDownstreamApi` automatically handles token acquisition and attaches the access token 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).- - ```csharp- 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- public 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.-- ```csharp- 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](#tab/messagehandler)--1. Install the required NuGet package:-- ```bash- dotnet add package Microsoft.Identity.Web.AgentIdentities- ```+1. 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](~/identity-platform/v2-admin-consent.md).+1. Open [Microsoft Graph Explorer](https://developer.microsoft.com/graph/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. -1. Configure your services to add authentication with agent identities and register HttpClient with `MicrosoftIdentityMessageHandler`:-- ```csharp- 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", client =>- {- client.BaseAddress = new Uri("https://api.example.com");- client.DefaultRequestHeaders.Add("Accept", "application/json");- 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();+ ```http+ GET https://graph.microsoft.com/v1.0/servicePrincipals/<agent-identity-object-id>/appRoleAssignments ``` -1. 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`.- - ```csharp- 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`.-- ```csharp- 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.- - ```csharp- // 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](#tab/authheaderprovider)--1. Install the required NuGet package:-- ```bash- dotnet add package Microsoft.Identity.Web.AgentIdentities- ```+ 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](/graph/api/serviceprincipal-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 ASP.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 app-only token is for the custom API.++```csharp+using System.Net.Http.Headers;+using Microsoft.Identity.Abstractions;+using Microsoft.Identity.Web;++var builder = WebApplication.CreateBuilder(args);++builder.Services+ .AddMicrosoftIdentityWebApiAuthentication(builder.Configuration)+ .EnableTokenAcquisitionToCallDownstreamApi()+ .AddInMemoryTokenCaches();++builder.Services.AddHttpClient();+builder.Services.AddAuthorization(options =>+{+ options.AddPolicy(+ "AgentUser",+ policy => policy.RequireRole("Agent.User"));+});++var app = builder.Build();++app.UseAuthentication();+app.UseAuthorization();++// Map the custom API endpoint before app.Run().+app.Run();+```++## Call the API -1. Configure your services to add authentication with agent identities:-- ```csharp- 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();+Use `IAuthorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync`. Pass the custom API's `.default` scope as a string. Replace `<custom-api-application-id-uri>` with the same URI you used for consent, and replace `https://api.contoso.com/data` with the API endpoint. The provider uses the configured client ID and credential directly.++Insert the following endpoint at the comment in `Program.cs`, before `app.Run()`. The required `using` directives are already at the top of the file. The endpoint gets an app-only authorization header and sends it to the custom API:++```csharp+app.MapGet("/custom-api", async (+ IAuthorizationHeaderProvider authorizationHeaderProvider,+ IHttpClientFactory httpClientFactory) =>+{+ string authorizationHeader = await authorizationHeaderProvider+ .CreateAuthorizationHeaderForAppAsync(+ "<custom-api-application-id-uri>/.default");++ HttpClient client = httpClientFactory.CreateClient();+ client.DefaultRequestHeaders.Authorization =+ AuthenticationHeaderValue.Parse(authorizationHeader);++ using HttpResponseMessage response =+ await client.GetAsync("https://api.contoso.com/data");+ response.EnsureSuccessStatusCode();++ return Results.Content(+ await response.Content.ReadAsStringAsync(),+ response.Content.Headers.ContentType?.ToString());+})+.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](control-user-access-agents.md) 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](/entra/identity-platform/howto-add-app-roles-in-apps).++## 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.++ ```dotnetcli+ dotnet run --urls https://localhost:5001 ```- - - Configure auth credentials in *appsettings.json*- - ```json- {- "AzureAd": {- "Instance": "https://login.microsoftonline.com/",- "TenantId": "your-tenant-id",- "ClientId": "your-blueprint-id",- "ClientCredentials": [- {- "SourceType": "ClientSecret",- "ClientSecret": "your-client-secret"- }- ]- }- }++ For a workstation, complete [Configure a local development credential](#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 the 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.++1. Use the upstream client from [Authenticate users to the agent API](aspnet-core-authenticate-users.md) to obtain an access token **for the agent API**, 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.+1. In a separate PowerShell terminal, call the agent endpoint:++ ```powershell+ $response = Invoke-WebRequest `+ -Uri "https://localhost:5001/custom-api" `+ -Headers @{ Authorization = "Bearer $env:AGENT_API_ACCESS_TOKEN" }+ $response.StatusCode+ $response.Content ``` -1. 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 - - ```csharp- 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);- - var response = await client.GetAsync("https://api.example.com/background");- var data = await 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";- var options = new AuthorizationHeaderProviderOptions()- .WithAgentIdentity(agentIdentity);- - // Acquire an access token for the agent identity- var authHeader = await _headerProvider.CreateAuthorizationHeaderForUserAsync(- scopes: new[] { "api://my-api/.default" }, options: options);- - // 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);- }- }- ```-- - For `WithAgentUserIdentity`, you call the API on behalf of a user using their UPN or OID.-- ```csharp- 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";- 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);- }- - // 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);- }- } - ```+ For an API 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. ----+1. Repeat the request without an authorization header: expect `401 Unauthorized` from the agent. With an otherwise valid agent API token that lacks `Agent.User`, expect `403 Forbidden` if the tenant issues that token. When assignment is required, the tenant might reject token issuance first.+1. 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 object ID, not the blueprint object ID, and check its `roles` claim. See [Validate Agent ID tokens in a downstream API](how-to-validate-agent-tokens-downstream-api.md). A successful token response alone doesn't prove these checks.+1. Test the downstream API's rejection of a token without its required role, using a separate test identity or fixture rather than removing production grants. Expect rejection at that API; don't infer its status from the agent's exception response.++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](how-to-validate-agent-tokens-downstream-api.md) ## Related content -- [Microsoft identity web](/entra/msal/dotnet/microsoft-identity-web/)-- [Call Microsoft Graph APIs](./call-api-custom.md)-- [Call Azure SDKs](./call-api-azure-services.md)+- [Build a platform that hosts an agent fleet](plan-agent-fleet.md)+- [Call a custom API as a user](aspnet-core-call-custom-api-as-user.md)+- [Agent ID best practices](best-practices-agent-id.md) 