Gå til indhold

User-assigned managed identity

Dette indhold er ikke tilgængeligt i dit sprog endnu.

In this article, you learn how to add or reference user-assigned managed identities (UMIs). You can add UMIs in your Aspire applications to securely access Azure resources. A UMI is a standalone Azure resource that you can assign to one or more service resources. UMIs give you more control over identity management and resource access.

To create a new user-assigned managed identity, use the AddAzureUserAssignedIdentity API in your distributed application builder:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sharedMi = builder.AddAzureUserAssignedIdentity("custom-umi");
// After adding all resources, run the app...
builder.Build().Run();

The preceding code creates a new managed identity named “custom-umi” that you can use with other resources in your application.

If you already have a managed identity, you can reference it using the PublishAsExisting method. This is useful when you want to use an identity that was created outside of your Aspire project.

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var miName = builder.AddParameter("miName");
var miResourceGroup = builder.AddParameter("miResourceGroup");
var sharedMi = builder.AddAzureUserAssignedIdentity("custom-umi")
.PublishAsExisting(miName, miResourceGroup);
// After adding all resources, run the app...
builder.Build().Run();

In the preceding example, you use parameters to provide the name and resource group of the existing identity. This allows you to reference the managed identity without creating a new one.

You can grant Azure roles to your managed identity using the WithRoleAssignments API. This lets your identity access other Azure resources, such as Azure Key Vault.

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sharedMi = builder.AddAzureUserAssignedIdentity("custom-umi");
builder.AddAzureKeyVault("secrets")
.WithRoleAssignments(sharedMi, BuiltInRole.Reader);
// After adding all resources, run the app...
builder.Build().Run();

In this example, you give the Reader role to the managed identity for the Key Vault resource. For more information about role assignments, see Manage Azure role assignments.

Spørg & svarSamarbejdFællesskabDiskutérSe