-
Notifications
You must be signed in to change notification settings - Fork 270
Calling APIs with Managed Identity
Jean-Marc Prieur edited this page Feb 20, 2024
·
5 revisions
Starting from Microsoft.Identity.Web version 2.17.0, apps can use managed identities to acquire a security token, call a downstream API, and/or call Microsoft Graph. This works with both system-assigned and user-assigned identities. If you'd like to learn more about managed identities for Azure resources, click here.
The below code is for a simple daemon application to call a downstream API on behalf of the client itself. For more details see daemon console app calling your own API
// More here ..
// Get the Token acquirer factory instance. By default it reads an appsettings.json
// file if it exists in the same folder as the app (make sure that the
// "Copy to Output Directory" property of the appsettings.json file is "Copy if newer").
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
// Create a downstream API service named 'MyApi' which comes loaded with several
// utility methods to make HTTP calls to the DownstreamApi configurations found
// in the "MyWebApi" section of your appsettings.json file.
tokenAcquirerFactory.Services.AddDownstreamApi("MyApi",
tokenAcquirerFactory.Configuration.GetSection("MyWebApi"));
var sp = tokenAcquirerFactory.Build();
// Extract the downstream API service from the 'tokenAcquirerFactory' service provider.
var api = sp.GetRequiredService<IDownstreamApi>();
// You can use the API service to make direct HTTP calls to your API. Token
// acquisition is handled automatically based on the configurations in your
// appsettings.json file.
var result = await api.GetForAppAsync<IEnumerable<TodoItem>