Integrate with Azure managed identities

Azure Active Directory managed identities help simplify secrets management for your cloud application. With a managed identity, you can set up your code to use the service principal that was created for the Azure compute 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, and Java Spring client libraries come with managed service identity (MSI) support built into them. Although you aren't required to use it, MSI eliminates the need for an access token that contains secrets. Your code has to know only the service endpoint for an app configuration store in order to access it. You can embed this URL in your code directly without the concern of exposing any secret.

This tutorial shows how you can take advantage of MSI to access App Configuration. It builds on the web app introduced in the quickstarts. Before you continue, finish Create an ASP.NET Core app with App Configuration 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 tutorial, 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.

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 as normal and then enable the feature.

  1. Create an app 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.

    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 Contributor. 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

Use a managed identity

  1. 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>"
    }
    
  2. Open Program.cs, and update the CreateWebHostBuilder method by replacing the config.AddAzureAppConfiguration() method.

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var settings = config.Build();
                config.AddAzureAppConfiguration(options =>
                    options.ConnectWithManagedIdentity(settings["AppConfig:Endpoint"]));
            })
            .UseStartup<Startup>();
    

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.

Use Azure Cloud Shell

Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell lets you use either bash or PowerShell to work with Azure services. You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

To launch Azure Cloud Shell:

Option Example/Link
Select Try It in the upper-right corner of a code block. Selecting Try It doesn't automatically copy the code to Cloud Shell. Example of Try It for Azure Cloud Shell
Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser.
Select the Cloud Shell button on the top-right menu bar in the Azure portal. Cloud Shell button in the Azure portal

To run the code in this article in Azure Cloud Shell:

  1. Launch Cloud Shell.
  2. Select the Copy button on a code block to copy the code.
  3. Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. Press Enter to run the code.

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

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>

To create a Git-enabled app instead, run az webapp create in Cloud Shell with the --deployment-local-git parameter.

az webapp create --name <app_name> --resource-group <group_name> --plan <plan_name> --deployment-local-git

The az webapp create command gives you something similar to the following output:

Local git is configured with url of 'https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git'
{
  "availabilityState": "Normal",
  "clientAffinityEnabled": true,
  "clientCertEnabled": false,
  "cloningInfo": null,
  "containerSize": 0,
  "dailyMemoryTimeQuota": 0,
  "defaultHostName": "<app_name>.azurewebsites.net",
  "deploymentLocalGitUrl": "https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git",
  "enabled": true,
  < JSON data removed for brevity. >
}

Deploy your project

Back 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 Git for your app.

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

App running in App Service

Use managed identity in other languages

App Configuration providers for .NET Framework and Java Spring also have built-in support for managed identity. In these cases, use your app configuration store's URL endpoint instead of its full connection string when you configure a provider. For example, for the .NET Framework console app created in the quickstart, 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. You can reuse them in the next tutorial.

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. The instructions for this quickstart used a resource group named AppConfigTestResources.
  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