Skip to main content

AZ-204 KeyVault

Rather than storing credentials in the application, we can use Azure keyvault to store user secrets. We can also use it to store 
1. secret , application that stores the secrets in files can be at risk if someone gets a peek at the source code. KV happens at runtime.
2. keys (for encryption/decryption) 
3. certificates (SSL certificates)
4. Storage accounts have access keys and KV can be used to manage them.
5. Azure VM disks encryption. We can encrypt the data stored on VMS using azure disk encryption.
6. In AKS 

DATA PROTECTION

 An Azure app service app can use certificates stored in KV to encrypt the data (in transit) or it can be used to encrypt the data stored in a database (in rest) 

Access control should follow the principle of least privilege.



Add new Resource => Keyvault









Create a Keyvault

























Using Keyvault when using azure AD






























NUGETS: Azure.Identity and Azure.Security.KeyVault.Secrets


_______________________________________________________________________________



AZURE CLI


if we need to use the cli then just keep using the -h along with the keywords that you need. 

To learn about keyvault.

Hit=>   az keyvault -h

All the options inside keyvault will be listed. Not to learn about a specitic option ex: create just use -h again

az keyvault create -h

 and just keep digging in..


____________________________________________________________________

Service Principle

To enable access control, we need to go through azure AD, which will give us a service principle that can be used to access the resources. Once KV gets a service priciple it can

We generate a service prinvipal for an application and then add that service principle to keyvault. 


We need to register our application with azure AD, which will give us a clientID and password , these credentials can be used to retrieve our secrets from KV.

The other approach is to use managed user identity, here we register our app against AD and we dont get a client ID and password. Then we configure KV to grant access to the app we created. THen the app can directly access the resource (KV in our case).


Generating Keys with azure Keyvault




Create a app service plan from portal or CLI. (kvtrialdemo in my case)
















From CLI

Create a web app on App Service  

az appservice plan create --name "kvtraildemo" --resource-group myResourceGroup --sku FREE

Then deploy a website,

Then use this command to register the app with azure AD.. Kvtrialdemo is the name of the app
service. now link this app service to keyvault.

register it in AD

az webapp identity assign --name "kvtraildemo" --resource-group "StorageTrialRG"

this will return a JSON
{ "principalId": "fe3bf1e3-b390-4e76-a93f-2f949fe3b543", "tenantId": "e2cdafd2-68d2-4ee9-b778-959662032860", "type": "SystemAssigned", "userAssignedIdentities": null }







































Create a Keyvault
























Create a secret inside keyvault
















Now create an access policy for this KV, that is who can access this resource.. We configure our web app here. So once our web app is deployed to azure it can automatically retrieve the secrets as it gets authenticated.

From CLI

Use the principalid to register the web app to KV as shown below


az keyvault set-policy --name "az204keyvaultSample" --object-id "fe3bf1e3-b390-4e76-a93f-2f949fe3b543" --secret-permissions get list


the object id is the principal id that we got while registering the app to azure AD. 

--name is the name of the KV

Or portal
































Controller:

Read the values from KV and display it in the page

 public IActionResult Index()
        {
            SecretClientOptions options = new SecretClientOptions()
            {
                Retry =
                {
                    Delay= TimeSpan.FromSeconds(2),
                    MaxDelay = TimeSpan.FromSeconds(16),
                    MaxRetries = 5,
                    Mode = RetryMode.Exponential
                }
            };
            var client = new SecretClient(new Uri("https://az204keyvaultsample.vault.azure.net/"), new DefaultAzureCredential()
            {

            }, options);

            KeyVaultSecret secret = client.GetSecret("SampleSecret");

            ViewData["Secret"] = secret.Value;
            return View();
        }

Result:
















But debugging in local environment doesnt work with the above code.. 

Now to get the value during development, just use the below code.


Microsoft.Azure.Services.AppAuthentication
Microsoft.Azure.KeyVault



  AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();

var keyvaultclient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));


// sample secret is the keyvault secret key
var secret = await keyvaultclient.GetSecretAsync("https://kvmanagedidenty.vault.azure.net/", "SampleSecret");

ViewData["Secret"] = secret.Value;
 return View(); 


ANOTHER APPROACH


Another way is in this video, but in this case we will get a clientid and secret which we will need to keep in our system. So it beats the purpose. 










Comments

Popular posts from this blog

App Role assignment to service principal --

 Using Ms Graph Rest API's Permissions One of the following permissions is required to call this API. To learn more, including how to choose permissions, see  Permissions . Permission type Permissions (from least to most privileged) Delegated (work or school account) AppRoleAssignment.ReadWrite.All and Application.Read.All, AppRoleAssignment.ReadWrite.All and Directory.Read.All, Application.ReadWrite.All, Directory.ReadWrite.All Delegated (personal Microsoft account) Not supported. Application AppRoleAssignment.ReadWrite.All and Application.Read.All, AppRoleAssignment.ReadWrite.All and Directory.Read.All, Application.ReadWrite.All, Directory.ReadWrite.All Create 2 app registrations. App role owner will contain the app role that will be assigned to a service principal. The  reader role in approleowner will be added to the approlesubscriber Setup postman to use the Oauth auth flow to get a token for MS Graph. ClientId:   Application (client) ID for approlesubscrib...

ASp.net core 3.1 identity

It is just an extension to cookie authentication. We get a UI, Tables, helper classes, two factor authentication etc. Even EF and its database constructs. So instead of writing code for all of this we can just use these in built features. Extending Default Identity Classes Add a class that inherits from    public class AppUser : IdentityUser     {         public string Behavior { get; set; }     } Also change the user type in login partial.cs under shared folder Then add migrations and update db using migrations. We can customize further.  services.AddDefaultIdentity<AppUser>(options =>              {                 options.SignIn.RequireConfirmedAccount = true;                 options.Password.RequireDigit = false;           ...

Get user groups

 string[] scopes = new string[] { "https://graph.microsoft.com/.default" };             string clientId = "";             string tenantId = "";             string secret = "";                        var options = new TokenCredentialOptions             {                 AuthorityHost = AzureAuthorityHosts.AzurePublicCloud             };             // https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential             try             {                 var clientSecretCredential = new ClientSecretCredential(                        ...