Integrate with Azure Managed Identities

Azure Active Directory managed identities simplify secrets management for your cloud application. With a managed identity, your code can use the service principal created for the Azure service it runs on. You use a managed identity instead of a separate credential stored in Azure Key Vault or a local connection string.

Azure App Configuration and its .NET Core, .NET Framework, and Java Spring client libraries have managed identity support built into them. Although you aren't required to use it, the managed identity eliminates the need for an access token that contains secrets. Your code can access the App Configuration store using only the service endpoint. You can embed this URL in your code directly without exposing any secret.

This article shows how you can take advantage of the managed identity to access App Configuration. It builds on the web app introduced in the quickstarts. Before you continue, Create an ASP.NET Core app with App Configuration first.

This article also shows how you can use the managed identity in conjunction with App Configuration's Key Vault references. With a single managed identity, you can seamlessly access both secrets from Key Vault and configuration values from App Configuration. If you wish to explore this capability, finish Use Key Vault References with ASP.NET Core first.

You can use any code editor to do the steps in this tutorial. Visual Studio Code is an excellent option available on the Windows, macOS, and Linux platforms.

In this article, you learn how to:

  • Grant a managed identity access to App Configuration.
  • Configure your app to use a managed identity when you connect to App Configuration.
  • Optionally, configure your app to use a managed identity when you connect to Key Vault through an App Configuration Key Vault reference.

Prerequisites

To complete this tutorial, you must have:

If you don't have an Azure subscription, create a free account before you begin.

Add a managed identity

To set up a managed identity in the portal, you first create an application and then enable the feature.

  1. Create an App Services instance in the Azure portal as you normally do. Go to it in the portal.

  2. Scroll down to the Settings group in the left pane, and select Identity.

  3. On the System assigned tab, switch Status to On and select Save.

  4. Answer Yes when prompted to enable system assigned managed identity.

    Set managed identity in App Service

Grant access to App Configuration

  1. In the Azure portal, select All resources and select the App Configuration store that you created in the quickstart.

  2. Select Access control (IAM).

  3. On the Check access tab, select Add in the Add role assignment card UI.

  4. Under Role, select App Configuration Data Reader. Under Assign access to, select App Service under System assigned managed identity.

  5. Under Subscription, select your Azure subscription. Select the App Service resource for your app.

  6. Select Save.

    Add a managed identity

  7. Optional: If you wish to grant access to Key Vault as well, follow the directions in Provide Key Vault authentication with a managed identity.

Use a managed identity

  1. Add a reference to the Azure.Identity package:

    dotnet add package Azure.Identity
    
  2. Find the endpoint to your App Configuration store. This URL is listed on the Access keys tab for the store in the Azure portal.

  3. Open appsettings.json, and add the following script. Replace <service_endpoint>, including the brackets, with the URL to your App Configuration store.

    "AppConfig": {
        "Endpoint": "<service_endpoint>"
    }
    
  4. Open Program.cs, and add a reference to the Azure.Identity and Microsoft.Azure.Services.AppAuthentication namespaces:

    using Azure.Identity;
    
  5. If you wish to access only values stored directly in App Configuration, update the CreateWebHostBuilder method by replacing the config.AddAzureAppConfiguration() method.

    Important

    CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your environment.

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var settings = config.Build();
                    config.AddAzureAppConfiguration(options =>
                        options.Connect(new Uri(settings["AppConfig:Endpoint"]), new ManagedIdentityCredential()));
                })
                .UseStartup<Startup>();
    
  6. To use both App Configuration values and Key Vault references, update Program.cs as shown below. This code creates a new KeyVaultClient using an AzureServiceTokenProvider and passes this reference to a call to the UseAzureKeyVault method.

            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .ConfigureAppConfiguration((hostingContext, config) =>
                    {
                        var settings = config.Build();
                        var credentials = new ManagedIdentityCredential();
    
                        config.AddAzureAppConfiguration(options =>
                        {
                            options.Connect(new Uri(settings["AppConfig:Endpoint"]), credentials)
                                    .ConfigureKeyVault(kv =>
                                    {
                                        kv.SetCredential(credentials);
                                    });
                        });
                    })
                    .UseStartup<Startup>();
    

    You can now access Key Vault references just like any other App Configuration key. The config provider will use the KeyVaultClient that you configured to authenticate to Key Vault and retrieve the value.

Prepare your repository

To get automatic builds from Azure App Service Kudu build server, make sure that your repository root has the correct files in your project.

Runtime Root directory files
ASP.NET (Windows only) *.sln, *.csproj, or default.aspx
ASP.NET Core *.sln or *.csproj
PHP index.php
Ruby (Linux only) Gemfile
Node.js server.js, app.js, or package.json with a start script
Python *.py, requirements.txt, or runtime.txt
HTML default.htm, default.html, default.asp, index.htm, index.html, or iisstart.htm
WebJobs <job_name>/run.<extension> under App_Data/jobs/continuous for continuous WebJobs, or App_Data/jobs/triggered for triggered WebJobs. For more information, see Kudu WebJobs documentation.
Functions See Continuous deployment for Azure Functions.

To customize your deployment, include a .deployment file in the repository root. For more information, see Customize deployments and Custom deployment script.

Note

If you develop in Visual Studio, let Visual Studio create a repository for you. The project is immediately ready to be deployed by using Git.

Deploy from local Git

The easiest way to enable local Git deployment for your app with the Kudu build server is to use Azure Cloud Shell.

Configure a deployment user

FTP and local Git can deploy to an Azure web app by using a deployment user. Once you configure your deployment user, you can use it for all your Azure deployments. Your account-level deployment username and password are different from your Azure subscription credentials.

To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell. Replace <username> and <password> with a deployment user username and password.

  • The username must be unique within Azure, and for local Git pushes, must not contain the ‘@’ symbol.
  • The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.
az webapp deployment user set --user-name <username> --password <password>

The JSON output shows the password as null. If you get a 'Conflict'. Details: 409 error, change the username. If you get a 'Bad Request'. Details: 400 error, use a stronger password.

Record your username and password to use to deploy your web apps.

Enable local Git with Kudu

If you don't have a local git repository for your app, you'll need to initialize one. To initialize a local git repository, run the following commands from your app's project directory:

git init
git add .
git commit -m "Initial version"

To enable local Git deployment for your app with the Kudu build server, run az webapp deployment source config-local-git in Cloud Shell.

az webapp deployment source config-local-git --name <app_name> --resource-group <group_name>

This command gives you something similar to the following output:

{
  "url": "https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git"
}

Deploy your project

In the local terminal window, add an Azure remote to your local Git repository. Replace <url> with the URL of the Git remote that you got from Enable local Git with Kudu.

git remote add azure <url>

Push to the Azure remote to deploy your app with the following command. When you're prompted for a password, enter the password you created in Configure a deployment user. Don't use the password you use to sign in to the Azure portal.

git push azure master

You might see runtime-specific automation in the output, such as MSBuild for ASP.NET, npm install for Node.js, and pip install for Python.

Browse to the Azure web app

Browse to your web app by using a browser to verify that the content is deployed.

http://<app_name>.azurewebsites.net

Use managed identity in other languages

App Configuration providers for .NET Framework and Java Spring also have built-in support for managed identity. You can use your store's URL endpoint instead of its full connection string when you configure one of these providers.

For example, you can update the .NET Framework console app created in the quickstart to specify the following settings in the App.config file:

    <configSections>
        <section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
    </configSections>

    <configBuilders>
        <builders>
            <add name="MyConfigStore" mode="Greedy" endpoint="${Endpoint}" type="Microsoft.Configuration.ConfigurationBuilders.AzureAppConfigurationBuilder, Microsoft.Configuration.ConfigurationBuilders.AzureAppConfiguration" />
            <add name="Environment" mode="Greedy" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment" />
        </builders>
    </configBuilders>

    <appSettings configBuilders="Environment,MyConfigStore">
        <add key="AppName" value="Console App Demo" />
        <add key="Endpoint" value ="Set via an environment variable - for example, dev, test, staging, or production endpoint." />
    </appSettings>

Clean up resources

If you plan to continue to the next tutorial, keep the resources you created in this quickstart for that you can reuse them.

If you're finished with the quickstart sample application, delete the Azure resources you created in this quickstart to avoid charges.

Important

Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure that you don't accidentally delete the wrong resource group or resources. If you created the resources for hosting this sample inside a resource group that contains resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.

  1. Sign in to the Azure portal, and select Resource groups.
  2. In the Filter by name box, enter the name of your resource group.
  3. In the result list, select the resource group, and either right-click the row or use the ellipsis (...) button to open the context menu.
  4. Select Delete resource group.
  5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select Delete.

After a few moments, the resource group and all its resources are deleted.

Next steps

In this tutorial, you added an Azure managed identity to streamline access to App Configuration and improve credential management for your app. To learn more about how to use App Configuration, continue to the Azure CLI samples.