Tutorial - Use Azure Key Vault with a virtual machine in .NET (2024)

  • Article

Azure Key Vault helps you to protect secrets such as API keys, the database connection strings you need to access your applications, services, and IT resources.

In this tutorial, you learn how to get a console application to read information from Azure Key Vault. Application would use virtual machine managed identity to authenticate to Key Vault.

The tutorial shows you how to:

  • Create a resource group.
  • Create a key vault.
  • Add a secret to the key vault.
  • Retrieve a secret from the key vault.
  • Create an Azure virtual machine.
  • Enable a managed identity for the Virtual Machine.
  • Assign permissions to the VM identity.

Before you begin, read Key Vault basic concepts.

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

Prerequisites

For Windows, Mac, and Linux:

  • Git
  • The .NET Core 3.1 SDK or later.
  • Azure CLI or Azure PowerShell

Create resources and assign permissions

Before you start coding you need to create some resources, put a secret into your key vault, and assign permissions.

Sign in to Azure

To sign in to Azure by using following command:

  • Azure CLI
  • Azure PowerShell
az login

Create a resource group and key vault

This quickstart uses a precreated Azure key vault. You can create a key vault by following the steps in the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart.

Alternatively, you can run these Azure CLI or Azure PowerShell commands.

Important

Each key vault must have a unique name. Replace <your-unique-keyvault-name> with the name of your key vault in the following examples.

  • Azure CLI
  • Azure PowerShell
az group create --name "myResourceGroup" -l "EastUS"az keyvault create --name "<your-unique-keyvault-name>" -g "myResourceGroup" --enable-rbac-authorization

Populate your key vault with a secret

Let's create a secret called mySecret, with a value of Success!. A secret might be a password, a SQL connection string, or any other information that you need to keep both secure and available to your application.

To add a secret to your newly created key vault, use the following command:

  • Azure CLI
  • Azure PowerShell
az keyvault secret set --vault-name "<your-unique-keyvault-name>" --name "mySecret" --value "Success!"

Create a virtual machine

Create a Windows or Linux virtual machine using one of the following methods:

WindowsLinux
Azure CLIAzure CLI
PowerShellPowerShell
Azure portalAzure portal

Assign an identity to the VM

Create a system-assigned identity for the virtual machine with the following example:

  • Azure CLI
  • Azure PowerShell
az vm identity assign --name <NameOfYourVirtualMachine> --resource-group <YourResourceGroupName>

Note the system-assigned identity that's displayed in the following code. The output of the preceding command would be:

{ "systemAssignedIdentity": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "userAssignedIdentities": {}}

Assign permissions to the VM identity

  • Azure CLI
  • Azure PowerShell

To grant your application permissions to your key vault through Role-Based Access Control (RBAC), assign a role using the Azure CLI command az role assignment create.

az role assignment create --role "Key Vault Secrets User" --assignee "<app-id>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"

Replace <app-id>, <subscription-id>, <resource-group-name> and <your-unique-keyvault-name> with your actual values. <app-id> is the Application (client) ID of your registered application in Microsoft Entra.

Sign in to the virtual machine

To sign in to the virtual machine, follow the instructions in Connect and sign in to an Azure Windows virtual machine or Connect and sign in to an Azure Linux virtual machine.

Set up the console app

Create a console app and install the required packages using the dotnet command.

Install .NET Core

To install .NET Core, go to the .NET downloads page.

Create and run a sample .NET app

Open a command prompt.

You can print "Hello World" to the console by running the following commands:

dotnet new console -n keyvault-console-appcd keyvault-console-appdotnet run

Install the package

From the console window, install the Azure Key Vault Secrets client library for .NET:

dotnet add package Azure.Security.KeyVault.Secrets

For this quickstart, you will need to install the following identity package to authenticate to Azure Key Vault:

dotnet add package Azure.Identity

Edit the console app

Open the Program.cs file and add these packages:

using System;using Azure.Core;using Azure.Identity;using Azure.Security.KeyVault.Secrets;

Add these lines, updating the URI to reflect the vaultUri of your key vault. Below code is using 'DefaultAzureCredential()' for authentication to key vault, which is using token from application managed identity to authenticate. It is also using exponential backoff for retries in case of key vault is being throttled.

 class Program { static void Main(string[] args) { string secretName = "mySecret"; string keyVaultName = "<your-key-vault-name>"; var kvUri = "https://<your-key-vault-name>.vault.azure.net"; SecretClientOptions options = new SecretClientOptions() { Retry = { Delay= TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential(),options); Console.Write("Input the value of your secret > "); string secretValue = Console.ReadLine(); Console.Write("Creating a secret in " + keyVaultName + " called '" + secretName + "' with the value '" + secretValue + "' ..."); client.SetSecret(secretName, secretValue); Console.WriteLine(" done."); Console.WriteLine("Forgetting your secret."); secretValue = ""; Console.WriteLine("Your secret is '" + secretValue + "'."); Console.WriteLine("Retrieving your secret from " + keyVaultName + "."); KeyVaultSecret secret = client.GetSecret(secretName); Console.WriteLine("Your secret is '" + secret.Value + "'."); Console.Write("Deleting your secret from " + keyVaultName + " ..."); client.StartDeleteSecret(secretName); System.Threading.Thread.Sleep(5000); Console.WriteLine(" done."); } }

Clean up resources

When they are no longer needed, delete the virtual machine and your key vault.

Next steps

Azure Key Vault REST API

Tutorial - Use Azure Key Vault with a virtual machine in .NET (2024)
Top Articles
Tata Steel (TATASTEEL.NSE) July 2024 Dividend - Stock Events
1 thousand US dollars currency-names.IQD.to Exchange Rate. Convert USD/IQD - Wise
Jack Doherty Lpsg
Public Opinion Obituaries Chambersburg Pa
Fan Van Ari Alectra
Play FETCH GAMES for Free!
Visitor Information | Medical Center
Sandrail Options and Accessories
Lost Ark Thar Rapport Unlock
Mylaheychart Login
Sportsman Warehouse Cda
Meg 2: The Trench Showtimes Near Phoenix Theatres Laurel Park
Dark Souls 2 Soft Cap
Moe Gangat Age
Persona 4 Golden Taotie Fusion Calculator
Wildflower1967
Labor Gigs On Craigslist
Byte Delta Dental
Equibase | International Results
Iroquois Amphitheater Louisville Ky Seating Chart
Ppm Claims Amynta
Rust Belt Revival Auctions
Target Minute Clinic Hours
Does Hunter Schafer Have A Dick
Fleet Farm Brainerd Mn Hours
Inkwell, pen rests and nib boxes made of pewter, glass and porcelain.
How do you get noble pursuit?
Kristy Ann Spillane
Proto Ultima Exoplating
1475 Akron Way Forney Tx 75126
Have you seen this child? Caroline Victoria Teague
Kaiserhrconnect
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Most popular Indian web series of 2022 (so far) as per IMDb: Rocket Boys, Panchayat, Mai in top 10
Deleted app while troubleshooting recent outage, can I get my devices back?
Gyeon Jahee
Teenage Jobs Hiring Immediately
Metra Schedule Ravinia To Chicago
Greater Keene Men's Softball
Ferguson Employee Pipeline
Bartow Qpublic
Go Bananas Wareham Ma
Post A Bid Monticello Mn
Tableaux, mobilier et objets d'art
Walmart 24 Hrs Pharmacy
Das schönste Comeback des Jahres: Warum die Vengaboys nie wieder gehen dürfen
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Blog Pch
Wvu Workday
Strange World Showtimes Near Century Federal Way
Ubg98.Github.io Unblocked
Lake County Fl Trash Pickup Schedule
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 6026

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.