Azure Certificate based Authentication from App Service to Access Key Vault

In this post I would like to demonstrate the usage of Certificate based Authentication from a deployed App Service in Azure & thereby accessing Azure Key Vault.

Control Flow

Following picture depicts the entire Control Flow.

image

Follow the steps for Certificate creation: LINK 1

  • Create Certificate
  • Export to .CER format
  • Export to .PFX format

Following are the App Service & App Registration activities LINK 2

  • Create App Service
  • Associate the .PFX Certificate
  • Create App Registration
  • Associate the .CER Certificate

Following are the Key Vault Activities LINK 3

  • Create Key Vault
  • Create Secret
  • Provide necessary permissions to the App Registration

Create the Code LINK 4

  • Create Web API Project
  • Load the certificate
  • Access the Key Vault
  • Deploy the Application

Test the application

image

Note This is a real-world scenario & hence steps & complexities are high.

Certificate vs Password

Certificate based Authentication is more secured than Password because:

  • Certificate is difficult to copy, re-generate & install – hence more security
    • Certificate based Authentication enforces that the Token is only provided to Certificate holder
  • Password can be copied easily & played back – hence less security

Common Errors

  • Forbidden – Add necessary permission for App Registration in the Key Vault
  • Not Found – This should be Key Vault Secret Name is invalid

Contact

For any information OR consulting please contact me through Linked-in.

References

https://docs.microsoft.com/en-us/azure/key-vault/key-vault-group-permissions-for-apps

NCRONTAB Expression in Web Jobs

NCRONTAB is the library used in Web Jobs & Azure Functions to prepare Scheduled Execution.  Using the library we can schedule jobs like:

  • Every day
  • Every day at 10 AM
  • Every Monday
  • Every Monday at 10AM
  • Every Year
  • Every Year December 31st at 12 PM

NCRONTAB Format

{second} {minute} {hour} {day} {month} {day-of-week}

Please note that the last parameter is NOT year

Asterisk

Use * to denote repeat

Examples

0 5 * * * * Every 5th minute
0 */5 * * * * Every 5 minutes
0 0 * * * * Every hour
0 0 */2 * * * Every 2 hour
0 0 9-17 * * * Every hour from 9AM to 5PM
0 30 9 * * * At 9:30 AM everyday
0 30 9 * * 1-5 At 9:30 AM every weekday
0 30 9 * Jan Mon At 9:30 AM every January Monday

More

https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=csharp#ncrontab-expressions

Create Web API Project to Access Certificate & Key Vault Secret

Create a new Web API project.image

Add package: Microsoft.Azure.KeyVault

Create a new Controller.  Add the following code.

public class KeyVaultController : Controller
{
     public IActionResult Index()
     {
         string result = string.Empty;

        try
         {
             result = new KeyVaultSecretProvider().GetKeyVaultSecret(“MySecret”);
         }
         catch (Exception ex)
         {
             result = ex.ToString();
         }

        return Content(result);
     }
}

Create a new class.  Add the following code.

using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace KeyVault_Cert_WebAPI.Controllers
{
     public class KeyVaultSecretProvider
     {
         public const string ClientID = “YOUR-CLIENT-ID”;
         public static string Thumbprint = “YOUR-THUMBPRINT”;
         public const string VaultURL = “https://YOUR-KEY-VAULT.vault.azure.net/”;
         public ClientAssertionCertificate Certificate { get; set; }

        public X509Certificate2 FindCertificateByThumbprint()
         {
             X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
             store.Open(OpenFlags.ReadOnly);
             X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, Thumbprint, false);
             store.Close();

            if (col == null || col.Count == 0)
                 throw new Exception(“ERROR: Certificate not found with thumbprint”);

            return col[0];
         }

        public void GetCertificate()
         {
             var clientAssertionCertPfx = FindCertificateByThumbprint();
             Certificate = new ClientAssertionCertificate(ClientID, clientAssertionCertPfx);
         }
         public async Task<string> GetAccessToken(string authority, string resource, string scope)
         {
             var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
             var result = await context.AcquireTokenAsync(resource, Certificate);

            return result.AccessToken;
         }

        public string GetKeyVaultSecret(string secretNode)
         {
             var secretUri = string.Format(“{0}{1}”, VaultURL + “secrets/”, secretNode);
             GetCertificate();
             var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));

            return keyVaultClient.GetSecretAsync(secretUri).Result.Value;
         }
     }
}

Deploy the Application

Publish the application to the same App Service we created in previous step.

Article Series

This post is part of an Article Series:

Azure Certificate based Authentication from App Service to Access Key Vault

Create Key Vault & Secret

In this post we can create a Key Vault & Secret.

Create Key Vault

Go to Azure > Key Vaults > Create new Key Vault

image

Copy the Key Vault URL.  You will need it in the upcoming step.

Create Secret

Go to the Secrets blade & Create a new secret.

image

Set Permissions

Go to Key Vault > Access Policies > Add Access Policy > Select App Registration

image

Congratulations!

Now we are ready to proceed with next step.

Article Series

This post is part of an Article Series:

Azure Certificate based Authentication from App Service to Access Key Vault

Azure Locks

Azure allows Locking the resource, resource group from accidental modifications OR deletions.

Types of Locks

There are 2 types of locks:

  • DELETE LOCK prevents deletion of resource
  • READONLY LOCK prevents modifications Or deletion of resource

LOCK Blade

The Lock Blade is available for all the resources:

  • App Service
  • Virtual Machines
  • Data Factory
  • etc.

image

Now let us create a Delete Lock.

image

Testing Lock

Now go to the App Service & Try deleting it.

You will get the following Message preventing it from deletion.

image

Note

This is a wonderful feature for Administrators & Prevents accidental deletion & modifications of the Azure Resource OR Resource Groups.

Create App Service, App Registration & Associate Certificates

In this post we can do the following:

  • Create App Service
  • Associate .PFX Certificate
  • Create App Registration
  • Associate .CER Certificate

Create App Service

Go to Azure > App Service > Create New App Service (At least B1 Plan required to have TLS settings)

image

Associate .PFX Certificate

Go to App Service > TLS Settings blade > Private key certificates tab > Upload our .PFX certificate

image

Note the Thumbprint of the certificate.  You will need it in the upcoming steps of the article-series.

Create App Registration

Go to Azure > Active Directory > App Registrations > Create New App Registration

image

Noe the Client ID & Tenant ID.  You will need it in the upcoming steps of the article-series.

Associate .CER Certificate

Now go to the Certificates & secrets blade and upload the .CER certificate.

image

Congratulations!

You are now ready with your App Service & App Registration along with the Certificates.

Note

Few notes on Certificates:

  • Issuer Information – owner information
  • Private Key – for encryption using one secret – faster
  • Public Key – for decryption using another secret  – slower & better reliable
  • Thumbprint – for identification
  • Password – for installation

References

https://www.geeksforgeeks.org/difference-between-private-key-and-public-key

Article Series

This post is part of an Article Series:

Azure Certificate based Authentication from App Service to Access Key Vault

How to Install a PFX Certificate through Code?

IIS

Go to IIS > Server Certificates > Export Certificate

C#

Install Certificate to Current User.

X509Certificate2 certificate = new X509Certificate2(“C:\\Certificates\\IISExported.pfx”, “Password”);
X509Store xstore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
xstore.Open(OpenFlags.ReadWrite);
xstore.Add(certificate);
xstore.Close();

Testing C#

Try getting the Certificate back.

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false);
if (col == null || col.Count == 0)
{
     Console.WriteLine(“ERROR: Certificate not found with thumbprint”);
}
else
     Console.WriteLine(“Found: ” + col[0].FriendlyName);

Create Certificates (.CER & .PFX)

Certificates provide better Authentication than Passwords.   Certificates has to be procured from Signing authorities & will be installed with application through Deployment Team.

Note However it is better for Developer to know all these – if anything screwed up can help back them.

Development Certificates

For development purposes we can use IIS Certificates.

Step 1: Create Certificate

Go to IIS > Server Certificates > Create Self-signed Certificate

image

You will get the new certificate listed as below.

image

Step 2: Export to .CER Format

Double-click on the certificate, Go to Details tab & Click Copy to File button.

Continue the wizard & You will get a .CER file output.

image

Step 3: Export to .PFX Format

Now right click on the item & click Export option.

Enter the Password & after export you will get a .PFX certificate.

image

Outputs

You can go the folder & see 2 files are created.

image

Summary

In this post we have seen how to create a certificate, export as .CER & .PFX file.