A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/azure/sdk/authentication/user-assigned-managed-identity below:

Authenticate Azure-hosted .NET apps to Azure resources using a user-assigned managed identity - .NET

Authenticate Azure-hosted .NET apps to Azure resources using a user-assigned managed identity

The recommended approach to authenticate an Azure-hosted app to other Azure resources is to use a managed identity. This approach is supported for most Azure services, including apps hosted on Azure App Service, Azure Container Apps, and Azure Virtual Machines. Discover more about different authentication techniques and approaches on the authentication overview page. In the sections ahead, you'll learn:

Essential managed identity concepts

A managed identity enables your app to securely connect to other Azure resources without the use of secret keys or other application secrets. Internally, Azure tracks the identity and which resources it's allowed to connect to. Azure uses this information to automatically obtain Microsoft Entra tokens for the app to allow it to connect to other Azure resources.

There are two types of managed identities to consider when configuring your hosted app:

The sections ahead describe the steps to enable and use a user-assigned managed identity for an Azure-hosted app. If you need to use a system-assigned managed identity, visit the system-assigned managed identities article for more information.

Create a user-assigned managed identity

User-assigned managed identities are created as standalone resources in your Azure subscription using the Azure portal or the Azure CLI. Azure CLI commands can be run in the Azure Cloud Shell or on a workstation with the Azure CLI installed.

  1. In the Azure portal, enter Managed identities in the main search bar and select the matching result under the Services section.

  2. On the Managed Identities page, select + Create.

  3. On the Create User Assigned Managed Identity page, select a subscription, resource group, and region for the user-assigned managed identity, and then provide a name.

  4. Select Review + create to review and validate your inputs.

  5. Select Create to create the user-assigned managed identity.

  6. After the identity is created, select Go to resource.

  7. On the new identity's Overview page, copy the Client ID value to use for later when you configure the application code.

Use the Azure CLI command az identity create to create a managed identity:

az identity create \
    --resource-group <resource-group-name> \
    --name <identity-name> \
    --query 'clientId' \
    --output json

The command output prints the client ID of the created user-assigned managed identity. The client ID is used to configure application code that relies on the identity.

You can always view the managed identity properties again using the az identity show command:

az identity show \
    --resource-group <your-resource-group> \
    --name <your-managed-identity-name> \
    --output json
Assign the managed identity to your app

A user-assigned managed identity can be associated with one or more Azure resources. All of the resources that use that identity gain the permissions applied through the identity's roles.

  1. In the Azure portal, navigate to the resource that hosts your app code, such as an Azure App Service or Azure Container App instance.

  2. From the resource's Overview page, expand Settings and select Identity from the navigation.

  3. On the Identity page, switch to the User assigned tab.

  4. Select + Add to open the Add user assigned managed identity panel.

  5. On the Add user assigned managed identity panel, use the Subscription dropdown to filter the search results for your identities. Use the User assigned managed identities search box to locate the user-assigned managed identity you enabled for the Azure resource hosting your app.

  6. Select the identity and choose Add at the bottom of the panel to continue.

The Azure CLI provides different commands to assign a user-assigned managed identity to different types of hosting services.

  1. To assign a user-assigned managed identity to a resource such as an Azure App Service web app using the Azure CLI, you'll need the resource ID of the identity. Use the az identity show command to retrieve the resource ID:

    az identity show \
        --resource-group <your-resource-group> \
        --name <your-managed-identity-name> \
        --output json \
        --query id
    
  2. Once you have the resource ID, use the Azure CLI command az <resourceType> identity assign command to associate the user-assigned managed identity with different resources, such as the following:

    For Azure App Service, use the Azure CLI command az webapp identity assign:

    az webapp identity assign \
        --resource-group <resource-group-name> \
        --name <webapp-name> \
        --identities <user-assigned-identity-resource-id>
    

    For Azure Container Apps, use the Azure CLI command az containerapp identity assign:

    az containerapp identity assign \
        --resource-group <resource-group-name> \
        --name <containerapp-name> \
        --identities <user-assigned-identity-resource-id>
    

    For Azure Virtual Machines, use the Azure CLI command az vm identity assign:

    az vm identity assign \
        --resource-group <resource-group-name> \
        --name <vm-name> \
        --identities <user-assigned-identity-resource-id>
    
Assign roles to the managed identity

Next, determine which roles your app needs and assign those roles to the managed identity. You can assign roles to a managed identity at the following scopes:

The following example shows how to assign roles at the resource group scope, since many apps manage all their related Azure resources using a single resource group.

  1. Navigate to the Overview page of the resource group that contains the app with the user-assigned managed identity.

  2. Select Access control (IAM) on the left navigation.

  3. On the Access control (IAM) page, select + Add on the top menu and then choose Add role assignment to navigate to the Add role assignment page.

  4. The Add role assignment page presents a tabbed, multi-step workflow to assign roles to identities. On the initial Role tab, use the search box at the top to locate the role you want to assign to the identity.

  5. Select the role from the results and then choose Next to move to the Members tab.

  6. For the Assign access to option, select Managed identity.

  7. For the Members option, choose + Select members to open the Select managed identities panel.

  8. On the Select managed identities panel, use the Subscription and Managed identity dropdowns to filter the search results for your identities. Use the Select search box to locate the user-assigned managed identity you enabled for the Azure resource hosting your app.

  9. Select the identity and choose Select at the bottom of the panel to continue.

  10. Select Review + assign at the bottom of the page.

  11. On the final Review + assign tab, select Review + assign to complete the workflow.

  1. To assign a role to a user-assigned managed identity using the Azure CLI, you'll need the principal ID of the identity. Use the az identity show command to retrieve the principal ID:

    az identity show \
        --resource-group <your-resource-group> \
        --name <your-managed-identity-name> \
        --output json \
        --query principalId
    
  2. Use the az role definition list command to explore which roles a managed identity can be assigned:

    az role definition list \
        --query "sort_by([].{roleName:roleName, description:description}, &roleName)" \
        --output table
    
  3. Assign a role to a managed identity using the az role assignment create command:

    az role assignment create \
        --assignee <your-principal-id> \
        --role <role-name> \
        --scope <scope>
    

    For example, to allow the managed identity with the ID of 99999999-9999-9999-9999-999999999999 read, write, and delete access to Azure Storage blob containers and data to all storage accounts in the msdocs-dotnet-sdk-auth-example resource group, assign the application service principal to the Storage Blob Data Contributor role using the following command:

    az role assignment create \
        --assignee 99999999-9999-9999-9999-999999999999 \
        --role "Storage Blob Data Contributor" \
        --scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/msdocs-dotnet-sdk-auth-example"
    

For information on assigning permissions at the resource or subscription level using the Azure CLI, see the article Assign Azure roles using the Azure CLI.

Authenticate to Azure services from your app

The Azure Identity library provides various credentials—implementations of TokenCredential adapted to supporting different scenarios and Microsoft Entra authentication flows. Since managed identity is unavailable when running locally, the steps ahead demonstrate which credential to use in which scenario:

Implement the code

Add the Azure.Identity package. In an ASP.NET Core project, also install the Microsoft.Extensions.Azure package:

In a terminal of your choice, navigate to the application project directory and run the following commands:

dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.Azure

Right-click your project in the Visual Studio Solution Explorer window and select Manage NuGet Packages. Search for Azure.Identity, and install the matching package. Repeat this process for the Microsoft.Extensions.Azure package.

Azure services are accessed using specialized client classes from the various Azure SDK client libraries. These classes and your own custom services should be registered for dependency injection so they can be used throughout your app. In Program.cs, complete the following steps to configure a client class for dependency injection and token-based authentication:

  1. Include the Azure.Identity and Microsoft.Extensions.Azure namespaces via using directives.
  2. Register the Azure service client using the corresponding Add-prefixed extension method.
  3. Pass an appropriate TokenCredential instance to the UseCredential method:

The client ID is used to identify a managed identity when configuring applications or services that need to authenticate using that identity.

  1. Retrieve the client ID assigned to a user-assigned managed identity using the following command:

    az identity show \
        --resource-group <resource-group-name> \
        --name <identity-name> \
        --query 'clientId'
    
  2. Configure ManagedIdentityCredential with the client ID:

    builder.Services.AddAzureClients(clientBuilder =>
    {
        clientBuilder.AddBlobServiceClient(
            new Uri("https://<account-name>.blob.core.windows.net"));
    
        TokenCredential credential = null;
    
        if (builder.Environment.IsProduction() || builder.Environment.IsStaging())
        {
            // Managed identity token credential discovered when running in Azure environments
            credential = new ManagedIdentityCredential(
                ManagedIdentityId.FromUserAssignedClientId("<client-id>"));
        } 
        else 
        {
            // Running locally on dev machine - DO NOT use in production or outside of local dev
            credential = new DefaultAzureCredential();
        }
    
        clientBuilder.UseCredential(credential);
    });
    

    An alternative to the UseCredential method is to provide the credential to the service client directly:

    TokenCredential credential = null;
    
    if (builder.Environment.IsProduction() || builder.Environment.IsStaging())
    {
        // Managed identity token credential discovered when running in Azure environments
        credential = new ManagedIdentityCredential(
            ManagedIdentityId.FromUserAssignedClientId("<client-id>"));
    }
    else
    {
        // Running locally on dev machine - DO NOT use in production or outside of local dev
        credential = new DefaultAzureCredential();
    }
    
    builder.Services.AddSingleton<BlobServiceClient>(_ =>
        new BlobServiceClient(
            new Uri("https://<account-name>.blob.core.windows.net"), credential));
    

The resource ID uniquely identifies the managed identity resource within your Azure subscription using the following structure:

/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}

Resource IDs can be built by convention, which makes them more convenient when working with a large number of user-assigned managed identities in your environment.

  1. Retrieve the resource ID for a user-assigned managed identity using the following command:

    az identity show \
        --resource-group <resource-group-name> \
        --name <identity-name> \
        --query 'id'
    
  2. Configure ManagedIdentityCredential with the resource ID:

    builder.Services.AddAzureClients(clientBuilder =>
    {
        clientBuilder.AddBlobServiceClient(
            new Uri("https://<account-name>.blob.core.windows.net"));
    
        TokenCredential credential = null;
    
        if (builder.Environment.IsProduction() || builder.Environment.IsStaging())
        {
            // Managed identity token credential discovered when running in Azure environments
            credential = new ManagedIdentityCredential(
                ManagedIdentityId.FromUserAssignedResourceId(new ResourceIdentifier("<resource-id>")));
        }
        else
        {
            // Running locally on dev machine - DO NOT use in production or outside of local dev
            credential = new DefaultAzureCredential();
        }
    
        clientBuilder.UseCredential(credential);
    });
    

    An alternative to the UseCredential method is to provide the credential to the service client directly:

    TokenCredential credential = null;
    
    if (builder.Environment.IsProduction() || builder.Environment.IsStaging())
    {
        // Managed identity token credential discovered when running in Azure environments
        credential = new ManagedIdentityCredential(
            ManagedIdentityId.FromUserAssignedResourceId(new ResourceIdentifier("<resource-id>")));
    }
    else
    {
        // Running locally on dev machine - DO NOT use in production or outside of local dev
        credential = new DefaultAzureCredential();
    }
    
    builder.Services.AddSingleton<BlobServiceClient>(_ =>
        new BlobServiceClient(
            new Uri("https://<account-name>.blob.core.windows.net"), credential));
    

A principal ID is another name for an object ID.

  1. Retrieve the object ID for a user-assigned managed identity using the following command:

    az identity show \
        --resource-group <resource-group-name> \
        --name <identity-name> \
        --query 'principalId'
    
  2. Configure ManagedIdentityCredential with the object ID:

    builder.Services.AddAzureClients(clientBuilder =>
    {
        clientBuilder.AddBlobServiceClient(
            new Uri("https://<account-name>.blob.core.windows.net"));
            
        TokenCredential credential = null;
    
        if (builder.Environment.IsProduction() || builder.Environment.IsStaging())
        {
            // Managed identity token credential discovered when running in Azure environments
            credential = new ManagedIdentityCredential(
                ManagedIdentityId.FromUserAssignedObjectId("<object-id>"));
        }
        else
        {
            // Running locally on dev machine - DO NOT use in production or outside of local dev
            credential = new DefaultAzureCredential();
        }
    
        clientBuilder.UseCredential(credential);
    });
    

    An alternative to the UseCredential method is to provide the credential to the service client directly:

    TokenCredential credential = null;
    
    if (builder.Environment.IsProduction() || builder.Environment.IsStaging())
    {
        // Managed identity token credential discovered when running in Azure environments
        credential = new ManagedIdentityCredential(
            ManagedIdentityId.FromUserAssignedObjectId("<object-id>"));
    }
    else
    {
        // Running locally on dev machine - DO NOT use in production or outside of local dev
        credential = new DefaultAzureCredential();
    }
    
    builder.Services.AddSingleton<BlobServiceClient>(_ =>
        new BlobServiceClient(
            new Uri("https://<account-name>.blob.core.windows.net"), credential));
    

The preceding code behaves differently depending on the environment where it's running:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4