|
| 1 | +--- |
| 2 | +title: Configure an Azure web application to read a secret from Key vault tutorial | Microsoft Docs |
| 3 | +description: Tutorial Configure an ASP.Net core application to read a secret from Key vault |
| 4 | +services: key-vault |
| 5 | +documentationcenter: |
| 6 | +author: barclayn |
| 7 | +manager: mbaldwin |
| 8 | + |
| 9 | +ms.assetid: 0e57f5c7-6f5a-46b7-a18a-043da8ca0d83 |
| 10 | +ms.service: key-vault |
| 11 | +ms.workload: identity |
| 12 | +ms.topic: tutorial |
| 13 | +ms.date: 05/17/2018 |
| 14 | +ms.author: barclayn |
| 15 | +ms.custom: mvc |
| 16 | +#Customer intent: As a developer I want to use Azure Key vault to store secrets for my app, so that they are kept secure. |
| 17 | +--- |
| 18 | +# Tutorial: Configure an Azure web application to read a secret from Key Vault |
| 19 | + |
| 20 | +In this tutorial, you go over the necessary steps for getting an Azure web application to read information from Key vault using managed service identities. You learn how to: |
| 21 | + |
| 22 | +> [!div class="checklist"] |
| 23 | +> * Create a Key Vault. |
| 24 | +> * Store a secret in Key Vault. |
| 25 | +> * Create an Azure Web Application. |
| 26 | +> * Enable managed service identities |
| 27 | +> * Grant the required permissions for the application to read data from Key vault. |
| 28 | +
|
| 29 | +If you don't have an Azure subscription, create a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F) before you begin. |
| 30 | + |
| 31 | +[!INCLUDE [cloud-shell-try-it.md](../../includes/cloud-shell-try-it.md)] |
| 32 | + |
| 33 | +If you choose to install and use the CLI locally, this tutorial requires that you are running the Azure CLI version 2.0.4 or later. Run `az --version` to find the version. If you need to install or upgrade, see [Install Azure CLI 2.0]( /cli/azure/install-azure-cli). |
| 34 | + |
| 35 | +To log in to the Azure using the CLI, you can type: |
| 36 | + |
| 37 | +```azurecli |
| 38 | +az login |
| 39 | +``` |
| 40 | + |
| 41 | +## Create resource group |
| 42 | + |
| 43 | +Create a resource group with the [az group create](/cli/azure/group#az-group-create) command. An Azure resource group is a logical container into which Azure resources are deployed and managed. |
| 44 | + |
| 45 | +The following example creates a resource group named *ContosoResourceGroup* in the *eastus* location. |
| 46 | + |
| 47 | +```azurecli |
| 48 | +# To list locations: az account list-locations --output table |
| 49 | +az group create --name "ContosoResourceGroup" --location "East US" |
| 50 | +``` |
| 51 | + |
| 52 | +The resource group you just created is used throughout this tutorial. |
| 53 | + |
| 54 | +## Create an Azure Key Vault |
| 55 | + |
| 56 | +Next you create a Key Vault in the resource group created in the previous step. Although “ContosoKeyVault” is used as the name for the Key Vault throughout this tutorial, you have to use a unique name. Provide the following information: |
| 57 | + |
| 58 | +* Vault name **ContosoKeyVault**. |
| 59 | +* Resource group name **ContosoResourceGroup**. |
| 60 | +* The location **East US**. |
| 61 | + |
| 62 | +```azurecli |
| 63 | +az keyvault create --name "ContosoKeyVault" --resource-group "ContosoResourceGroup" --location "East US" |
| 64 | +``` |
| 65 | + |
| 66 | +The output of this command shows properties of the newly created Key Vault. Take note of the two properties listed below: |
| 67 | + |
| 68 | +* **Vault Name**: In the example, this is **ContosoKeyVault**. You will use the name of your Key Vault for all Key Vault commands. |
| 69 | +* **Vault URI**: In the example, this is https://<YourKeyVaultName>.vault.azure.net/. Applications that use your vault through its REST API must use this URI. |
| 70 | + |
| 71 | +>[!IMPORTANT] |
| 72 | +> If you get the error Parameter 'vault_name' must conform to the following pattern: '^[a-zA-Z0-9-]{3,24}$' The -name param value was not unique or did not conform to a string composed of alpha-numeric characters from 3 to 24 long. |
| 73 | +
|
| 74 | +At this point, your Azure account is the only one authorized to perform any operations on this new vault. |
| 75 | + |
| 76 | +## Add a secret to key vault |
| 77 | + |
| 78 | +We're adding a secret to help illustrate how this works. You could be storing a SQL connection string or any other information that you need to keep securely but make available to your application. In this tutorial, the password will be called **AppSecret** and will store the value of **MySecret** in it. |
| 79 | + |
| 80 | +Type the commands below to create a secret in Key Vault called **AppSecret** that will store the value **MySecret**: |
| 81 | + |
| 82 | +```azurecli |
| 83 | +az keyvault secret set --vault-name "ContosoKeyVault" --name "AppSecret" --value "MySecret" |
| 84 | +``` |
| 85 | + |
| 86 | +To view the value contained in the secret as plain text: |
| 87 | + |
| 88 | +```azurecli |
| 89 | +az keyvault secret show --name "AppSecret" --vault-name "ContosoKeyVault" |
| 90 | +``` |
| 91 | + |
| 92 | +This command shows the secret information including the URI. After completing these steps, you should have a URI to a secret in an Azure Key Vault. Make note of this information. You need it in a later step. |
| 93 | + |
| 94 | +## Create a web app |
| 95 | + |
| 96 | +In this section you create an ASP.NET MVC application and deploy it in Azure as a Web App. For more information about Azure Web Apps, see [Web Apps overview](../app-service/app-service-web-overview.md). |
| 97 | + |
| 98 | +1. In Visual Studio, create a project by selecting **File > New > Project**. |
| 99 | + |
| 100 | +2. In the **New Project** dialog, select **Visual C# > Web > ASP.NET Core Web Application**. |
| 101 | + |
| 102 | +3. Name the application **WebKeyVault**, and then select **OK**. |
| 103 | + >[!IMPORTANT] |
| 104 | + > You must name the app WebKeyVault so the code you copy and paste will match the namespace. If you named the site anything else you will need to modify the code to match the site name. |
| 105 | +
|
| 106 | +  |
| 107 | + |
| 108 | +4. You can deploy any type of ASP.NET Core web app to Azure. For this tutorial, select the **Web Application** template, and make sure authentication is set to **No Authentication**. |
| 109 | + |
| 110 | +  |
| 111 | + |
| 112 | +5. Select **OK**. |
| 113 | + |
| 114 | +6. Once the ASP.NET Core project is created, the ASP.NET Core welcome page is displayed, providing numerous links to resources to help you get started. |
| 115 | + |
| 116 | +7. From the menu, select **Debug > Start without Debugging** to run the web app locally. |
| 117 | + |
| 118 | +## Modify the web app |
| 119 | + |
| 120 | +There are two NuGet packages that your web application needs to have installed. To install them, follow the steps below: |
| 121 | + |
| 122 | +1. In solution explorer right-click on your website name. |
| 123 | +2. Select **Manage NuGet packages for solution...** |
| 124 | +3. Select the check box next to the search box. **Include prerelease** |
| 125 | +4. Search for the two NuGet packages listed below and accept for them to be added to your solution: |
| 126 | + |
| 127 | + * [Microsoft.Azure.Services.AppAuthentication](https://www.nuget.org/packages/Microsoft.Azure.Services.AppAuthentication) - makes it easy to fetch access tokens for Service-to-Azure-Service authentication scenarios. |
| 128 | + * [Microsoft.Azure.KeyVault](https://www.nuget.org/packages/Microsoft.Azure.KeyVault) - contains methods for interacting with Key Vault. |
| 129 | + |
| 130 | +5. Use the Solution Explorer to open `Program.cs` and replace the contents of the Program.cs file with the following code. Substitute ```<YourKeyVaultName>``` with the name of your key vault: |
| 131 | + |
| 132 | + ```csharp |
| 133 | + |
| 134 | + using Microsoft.AspNetCore; |
| 135 | + using Microsoft.AspNetCore.Hosting; |
| 136 | + using Microsoft.Azure.KeyVault; |
| 137 | + using Microsoft.Azure.Services.AppAuthentication; |
| 138 | + using Microsoft.Extensions.Configuration; |
| 139 | + using Microsoft.Extensions.Configuration.AzureKeyVault; |
| 140 | + |
| 141 | + namespace WebKeyVault |
| 142 | + { |
| 143 | + public class Program |
| 144 | + { |
| 145 | + public static void Main(string[] args) |
| 146 | + { |
| 147 | + BuildWebHost(args).Run(); |
| 148 | + } |
| 149 | + |
| 150 | + public static IWebHost BuildWebHost(string[] args) => |
| 151 | + WebHost.CreateDefaultBuilder(args) |
| 152 | + .ConfigureAppConfiguration((ctx, builder) => |
| 153 | + { |
| 154 | + var keyVaultEndpoint = GetKeyVaultEndpoint(); |
| 155 | + if (!string.IsNullOrEmpty(keyVaultEndpoint)) |
| 156 | + { |
| 157 | + var azureServiceTokenProvider = new AzureServiceTokenProvider(); |
| 158 | + var keyVaultClient = new KeyVaultClient( |
| 159 | + new KeyVaultClient.AuthenticationCallback( |
| 160 | + azureServiceTokenProvider.KeyVaultTokenCallback)); |
| 161 | + builder.AddAzureKeyVault( |
| 162 | + keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager()); |
| 163 | + } |
| 164 | + } |
| 165 | + ).UseStartup<Startup>() |
| 166 | + .Build(); |
| 167 | + |
| 168 | + private static string GetKeyVaultEndpoint() => "https://<YourKeyVaultName>.vault.azure.net"; |
| 169 | + } |
| 170 | + } |
| 171 | + ``` |
| 172 | + |
| 173 | +6. Use Solution Explorer to navigate to the **Pages** section and open `About.cshtml`. Replace the contents of **About.cshtml.cs** with the code below: |
| 174 | + |
| 175 | + ```csharp |
| 176 | + |
| 177 | + using Microsoft.AspNetCore.Mvc.RazorPages; |
| 178 | + using Microsoft.Extensions.Configuration; |
| 179 | + |
| 180 | + namespace WebKeyVault.Pages |
| 181 | + { |
| 182 | + public class AboutModel : PageModel |
| 183 | + { |
| 184 | + public AboutModel(IConfiguration configuration) |
| 185 | + { |
| 186 | + _configuration = configuration; |
| 187 | + } |
| 188 | + |
| 189 | + private readonly IConfiguration _configuration = null; |
| 190 | + public string Message { get; set; } |
| 191 | + |
| 192 | + public void OnGet() |
| 193 | + { |
| 194 | + Message = "My key val = " + _configuration["AppSecret"]; |
| 195 | + } |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + ``` |
| 200 | + |
| 201 | +7. From the main menu, choose **Debug** > **Start without Debugging**. When the browser appears, navigate to the **About** page. The value for the AppSecret is displayed. |
| 202 | + |
| 203 | +>[!IMPORTANT] |
| 204 | +> If you get a HTTP Error 502.5 - Process Failure message |
| 205 | +> > then verify the name of the Key Vault specified in `Program.cs` |
| 206 | + |
| 207 | +## Publish the web application to Azure |
| 208 | + |
| 209 | +1. Above the editor, select **WebKeyVault**. |
| 210 | +2. Select **Publish** then **Start**. |
| 211 | +3. Create a new **App Service**, select **Publish**. |
| 212 | +4. Select **Create**. |
| 213 | + |
| 214 | +>[!IMPORTANT] |
| 215 | +> A browser window opens and you will see a 502.5 - Process Failure message. This is expected. You will need to grant the application identity rights to read secrets from Key Vault. |
| 216 | + |
| 217 | +## Enable Managed Service Identity |
| 218 | + |
| 219 | +Azure Key Vault provides a way to securely store credentials and other keys and secrets, but your code needs to authenticate to Key Vault to retrieve them. Managed Service Identity (MSI) makes solving this problem simpler by giving Azure services an automatically managed identity in Azure Active Directory (Azure AD). You can use this identity to authenticate to any service that supports Azure AD authentication, including Key Vault, without having any credentials in your code. |
| 220 | + |
| 221 | +1. Return to the Azure CLI |
| 222 | +2. Run the assign-identity command to create the identity for this application: |
| 223 | + |
| 224 | +```azurecli |
| 225 | +az webapp identity assign --name "WebKeyVault" --resource-group "ContosoResourcegroup" |
| 226 | +``` |
| 227 | + |
| 228 | +>[!NOTE] |
| 229 | +>This command is the equivalent of going to the portal and switching **Managed service identity** to **On** in the web application properties. |
| 230 | + |
| 231 | +## Grant rights to the application identity |
| 232 | + |
| 233 | +Using the Azure portal, go to the Key Vault's access policies, and grant yourself Secret Management access to the Key Vault. This will allow you to run the application on your local development machine. |
| 234 | + |
| 235 | +1. Search for your Key Vault in the **Search Resources** dialog box in the Azure portal. |
| 236 | +2. Select **Access policies**. |
| 237 | +3. Select **Add New**, in the **Secret permissions** section select **Get** and **List**. |
| 238 | +4. Select **Select Principal**, and add the application identity. It will have the same name as the application. |
| 239 | +5. Choose **Ok**. |
| 240 | + |
| 241 | +Now your account in Azure and the application identity have rights to read information from Key Vault. When you refresh the page, you should see the landing page of the site. If you select **About**, you see the value you stored in Key Vault. |
| 242 | + |
| 243 | +## Clean up resources |
| 244 | + |
| 245 | +To delete a resource group and all its resources, use the **az group delete** command. |
| 246 | + |
| 247 | + ```azurecli |
| 248 | + az group delete -n "ContosoResourceGroup" |
| 249 | + ``` |
| 250 | + |
| 251 | +## Next steps |
| 252 | + |
| 253 | +> [!div class="nextstepaction"] |
| 254 | +> [Azure Key Vault Developer's Guide](key-vault-developers-guide.md) |
0 commit comments