Azure Service Principle with Azure Identity

Last post we talked about how to use C# to extract Azure Key Vault credentials. Further more it's ideal to run without problem on localhost, but when you deploy it to the cloud it will throw an exception complaining about authorization with Azure, and here is why.

At local environment, application will find and use the Azure credentials if you use DefaultAzureCredential method. Inside fresh-everytime docker environment there is no way it can retrieve those credentials. We have to do some extra work for it.

Create Azure Roll-Based Access Control

This blog post we are going to talk about how to create Azure Roll-based access control, as known as rbac client, and put it into work.

First of all you will have to install Azure Command-line Interface in your machine, if you have not done this before you can refer this official documentation by Microsoft. After everything is setup correctly, follow this tutorial and create your very first rbac client.

In case you forgot, you should definitely keep those credential somewhere safe. For me, I just simply put it into MSSQL database.

The credential should looks like this when created:

{
  "appId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "displayName": "KeyVaultUser",
  "password": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "tenant": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

After you store it somewhere safe, inside your program you should replace DefaultAzureCredential() method with ClientSecretCredential(tenantId, clientId, clientSecret);

Setup RBAC permission on Azure

Before we modify our code, we should head to Azure Portal, find your desire Key Vault to use, and give the client you just created some permissions.

Azure Portal Key Vault Add Access Policy

On the picture above you can see. After we entered Key Vault, click the "Access Policies" option on the left, and click "+ Add Access Policy" on the right.

Add access policy

As you can see above. Since we only need our client to retrieve Key, Secret and Certificates, We only give the rbac client "Get" permission, and it is consider a best practice.

Never give extra permission unless you know what you are doing.

After setting it up, we can start modify our code!

Code Modification

When preparation above is finished, we are going to change how program retrieve credentials. By doing so, we are going to use ClientSecretCredential method to setup our credential.

This is just a POC console application so I hard-coded credential when create this object. Ideally you should retrieve this information somewhere safe, either from Environment Variable or Database, pick your favorite.

After finished your modification, run the console application or whatever method you choose to, you should see it retrieve credentials from Azure Key Vault successfully.