Edit

Share via


Configure passwordless connections between multiple Azure apps and services

Applications often require secure connections between multiple Azure services simultaneously. For example, an enterprise Azure App Service instance might connect to several different storage accounts, an Azure SQL database instance, a Service Bus, and more.

Managed identities are the recommended authentication option for secure, passwordless connections between Azure resources. Developers don't have to manually track and manage many different secrets for managed identities, since most of these tasks are handled internally by Azure. This tutorial explores how to manage connections between multiple services using managed identities and the Azure Identity client library.

Compare the types of managed identities

Azure provides the following types of managed identities:

  • System-assigned managed identities are directly tied to a single Azure resource. When you enable a system-assigned managed identity on a service, Azure will create a linked identity and handle administrative tasks for that identity internally. When the Azure resource is deleted, the identity is also deleted.
  • User-assigned managed identities are independent identities that are created by an administrator and can be associated with one or more Azure resources. The lifecycle of the identity is independent of those resources.

You can read more about best practices and when to use system-assigned versus user-assigned managed identities in managed identity best practice recommendations.

Explore DefaultAzureCredential

Managed identities are most easily implemented in your application code via a class called DefaultAzureCredential from the Azure Identity client library. DefaultAzureCredential supports multiple authentication mechanisms and automatically determines which should be used at runtime. Learn more about DefaultAzureCredential for the following ecosystems:

Connect an Azure-hosted app to multiple Azure services

Imagine you're tasked with connecting an existing app to multiple Azure services and databases using passwordless connections. The application is an ASP.NET Core Web API hosted on Azure App Service, though the steps below apply to other Azure hosting environments as well, such as Azure Spring Apps, Virtual Machines, Container Apps, and AKS.

This tutorial applies to the following architectures, though it can be adapted to many other scenarios as well through minimal configuration changes.

Diagram showing the user assigned identity relationships.

The following steps demonstrate how to configure an app to use a system-assigned managed identity and your local development account to connect to multiple Azure Services.

Create a system-assigned managed identity

  1. In the Azure portal, navigate to the hosted application that you would like to connect to other services.

  2. On the service overview page, select Identity.

  3. Toggle the Status setting to On to enable a system assigned managed identity for the service.

    Screenshot showing how to assign a system-assigned managed identity.

Assign roles to the managed identity for each connected service

  1. Navigate to the overview page of the storage account you would like to grant access your identity access to.

  2. Select Access Control (IAM) from the storage account navigation.

  3. Choose + Add and then Add role assignment.

    Screenshot showing how to locate the Azure portal section for assigning a role to a system-assigned managed identity.

  4. In the Role search box, search for Storage Blob Data Contributor, which grants permissions to perform read and write operations on blob data. You can assign whatever role is appropriate for your use case. Select the Storage Blob Data Contributor from the list and choose Next.

  5. On the Add role assignment screen, for the Assign access to option, select Managed identity. Then choose +Select members.

  6. In the flyout, search for the managed identity you created by entering the name of your App Service. Select the system-assigned identity, and then choose Select to close the flyout menu.

    Screenshot showing how to assign a role to a system-assigned managed identity in the Azure portal.

  7. Select Next a couple times until you're able to select Review + assign to finish the role assignment.

  8. Repeat this process for the other services you would like to connect to.

Local development considerations

You can also enable access to Azure resources for local development by assigning roles to a user account the same way you assigned roles to your managed identity.

  1. After assigning the Storage Blob Data Contributor role to your managed identity, under Assign access to, this time select User, group or service principal. Choose + Select members to open the flyout menu again.

  2. Search for the user@domain account or Microsoft Entra security group you would like to grant access to by email address or name, and then select it. This should be the same account you use to sign-in to your local development tooling with, such as Visual Studio or the Azure CLI.

Note

You can also assign these roles to a Microsoft Entra security group if you're working on a team with multiple developers. You can then place any developer inside that group who needs access to develop the app locally.

Implement the application code

  1. In your project, install the Azure.Identity package. This library provides DefaultAzureCredential. You can also add any other Azure libraries that are relevant to your app. For this example, the Azure.Storage.Blobs and Azure.Messaging.ServiceBus packages are added to connect to Blob Storage and Service Bus, respectively.

    dotnet add package Azure.Identity
    dotnet add package Azure.Messaging.ServiceBus
    dotnet add package Azure.Storage.Blobs
    
  2. Instantiate service clients for the Azure services to which your app must connect. The following code sample interacts with Blob Storage and Service Bus using the corresponding service clients.

    using Azure.Identity;
    using Azure.Messaging.ServiceBus;
    using Azure.Storage.Blobs;
    
    // Create DefaultAzureCredential instance that uses system-assigned managed identity
    // in the underlying ManagedIdentityCredential.
    DefaultAzureCredential credential = new();
    
    BlobServiceClient blobServiceClient = new(
        new Uri("https://<your-storage-account>.blob.core.windows.net"),
        credential);
    
    ServiceBusClient serviceBusClient = new("<your-namespace>", credential);
    ServiceBusSender sender = serviceBusClient.CreateSender("producttracking");
    

When this code runs locally, DefaultAzureCredential searches its credential chain for the first available credentials. If the Managed_Identity_Client_ID environment variable is null locally, a credential corresponding to a locally installed developer tool is used. For example, Azure CLI or Visual Studio. To learn more about this process, see section Explore DefaultAzureCredential.

When the application is deployed to Azure, DefaultAzureCredential automatically retrieves the Managed_Identity_Client_ID variable from the App Service environment. That value becomes available when a managed identity is associated with your app.

This overall process ensures that your app can run securely locally and in Azure without the need for any code changes.

Connect multiple apps using multiple managed identities

Although the apps in the previous example shared the same service access requirements, real-world environments are often more nuanced. Consider a scenario where multiple apps connect to the same storage accounts, but two of the apps also access different services or databases.

Diagram showing multiple user-assigned managed identities.

To configure this setup in your code, ensure your application registers separate service clients to connect to each storage account or database. Reference the correct managed identity client IDs for each service when configuring DefaultAzureCredential. The following code samples configure these Azure service connections:

  • Two connections to separate storage accounts using a shared user-assigned managed identity
  • A connection to Azure Cosmos DB and Azure SQL services using a second user-assigned managed identity. This managed identity is shared when the Azure SQL client driver allows for it. For more information, see the code comments.
  1. In your project, install the required packages. The Azure Identity library provides DefaultAzureCredential.

    dotnet add package Azure.Identity
    dotnet add package Azure.Storage.Blobs
    dotnet add package Microsoft.Azure.Cosmos
    dotnet add package Microsoft.Data.SqlClient
    
  2. Add the following to your code:

    using Azure.Core;
    using Azure.Identity;
    using Azure.Storage.Blobs;
    using Microsoft.Azure.Cosmos;
    using Microsoft.Data.SqlClient;
    
    string clientIdStorage =
        Environment.GetEnvironmentVariable("Managed_Identity_Client_ID_Storage")!;
    
    // Create a DefaultAzureCredential instance that configures the underlying
    // ManagedIdentityCredential to use a user-assigned managed identity.
    DefaultAzureCredential credentialStorage = new(
        new DefaultAzureCredentialOptions
        {
            ManagedIdentityClientId = clientIdStorage,
        });
    
    // First Blob Storage client
    BlobServiceClient blobServiceClient1 = new(
        new Uri("https://<receipt-storage-account>.blob.core.windows.net"),
        credentialStorage);
    
    // Second Blob Storage client
    BlobServiceClient blobServiceClient2 = new(
        new Uri("https://<contract-storage-account>.blob.core.windows.net"),
        credentialStorage);
    
    string clientIdDatabases =
        Environment.GetEnvironmentVariable("Managed_Identity_Client_ID_Databases")!;
    
    // Create a DefaultAzureCredential instance that configures the underlying
    // ManagedIdentityCredential to use a user-assigned managed identity.
    DefaultAzureCredential credentialDatabases = new(
        new DefaultAzureCredentialOptions
        {
            ManagedIdentityClientId = clientIdDatabases,
        });
    
    // Create an Azure Cosmos DB client
    CosmosClient cosmosClient = new(
        Environment.GetEnvironmentVariable("COSMOS_ENDPOINT", EnvironmentVariableTarget.Process),
        credentialDatabases);
    
    // Open a connection to Azure SQL
    string connectionString =
        $"Server=<azure-sql-hostname>.database.windows.net;User Id={clientIdDatabases};Authentication=Active Directory Default;Database=<database-name>";
    
    using (SqlConnection connection = new(connectionString)
    {
        AccessTokenCallback = async (authParams, cancellationToken) =>
        {
            const string defaultScopeSuffix = "/.default";
            string scope = authParams.Resource.EndsWith(defaultScopeSuffix)
                ? authParams.Resource
                : $"{authParams.Resource}{defaultScopeSuffix}";
            AccessToken token = await credentialDatabases.GetTokenAsync(
                new TokenRequestContext([scope]),
                cancellationToken);
    
            return new SqlAuthenticationToken(token.Token, token.ExpiresOn);
        }
    })
    {
        connection.Open();
    }
    

You can also associate a user-assigned managed identity and a system-assigned managed identity to a resource simultaneously. This can be useful in scenarios where all of the apps require access to the same shared services, but one of the apps also has a specific dependency on an additional service. Using a system-assigned managed identity also ensures that the identity tied to that specific app is deleted when the app is deleted, which can help keep your environment clean.

Diagram showing user-assigned and system-assigned managed identities.

These types of scenarios are explored in more depth in the managed identity best practice recommendations.

Next steps

In this tutorial, you learned how to migrate an application to passwordless connections. Read the following resources to explore the concepts discussed in this article in more depth: