Alica's dev blog
How to configure DownstreamApi in ASP.NET

Recently I worked on introducing Managed identity authentication to an ASP.NET WebApi. One of the things that you need to deal with in the code is requesting and caching tokens for that identity, so that you can make auhtenticated requests to that API.

You can write the code yourself or you can use DownstreamApi from Microsoft.Identity.Web package. This is probably not very widely used because I struggled to find one page which would tell me all the steps that I need to do in order to correctly configure it and make it work.

Based on my experience, I would even suggest rather using your own code (e.g. custom HTTP handler which will take care of the tokens) than DownstreamApi, because it is not very transparent and can be hard to configure – for example, I struggled with configuration of the serializer options. However, if you still want/need to use it, here are all the necessary steps in one place.

appsettings.json

Add the following section:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com",
    "TenantId": <your Microsoft Entra tenant ID>,
    "ClientId": <your app registration client ID>
},
"MyWebApi": {
    "RequestAppToken": true,
    "AcquireTokenOptions": {
        "ManagedIdentity": {
            "UserAssignedClientId": <your Managed identity client ID> // or omit the line when using system-assigned
        }
    },
    "Scopes": [<your scope 1>, <your scope 2>s]
}

Startup.cs

In ConfigureServices(), add the following code:

var myWebApiConfigSection = config.GetSection("MyWebApi");
var azureAdConfigSection = config.GetSection("AzureAd");

// these services are necessary for DownstreamApi to work
services.AddAuthorization();
services.AddRouting();
services.AddHttpContextAccessor();

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(azureAdConfigSection)
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddDownstreamApi("MyWebApi", myWebApiConfigSection)
    .AddInMemoryTokenCaches();

Last modified on 2025-11-18