AWS Secret Key Manager And Cache Implementation With .NET

Introduction

In this blog, we are discussing the implementation of AWS secret key manager with cache mechanism. Using .NET. AWS secret key manager enables us to easily create and manage the confidential data that we use in our applications. Instead of embedding our credentials or database connection string to source code we can read or fetch dynamically using this feature. We can automatically and frequently rotate the keys without any deployment. All the secrets are encrypted with AWS KMS.

Here is my confidential or sensitive data and it contains an IP address, username, password. Please check the below snapshot. 

Aws Secret Key Manager And Cache Implementation with .NET

Step 1

First, we need to login into the AWS console and search for a secret key manager. Please check the below snapshot. Just click on Store a new secret button.

Aws Secret Key Manager And Cache Implementation with .NET

For example, usually, we use to store the database connection string in our app settings or web.config file but since it is confidential data I'm going to store it in secret key manager and reading in JSON format.

Step 2 

After clicking on the store a new secret button, the AWS console redirects to the "Store a new Secret" wizard. The first step is to choose the type of secret, and set its value. We'll be using the "Other type of secret" and will store the plaintext value. We'll leave the encryption as the default for now. Please check the below snapshot, I’m adding data to the secret key manager. 

Aws Secret Key Manager And Cache Implementation with .NET

Once we click on the Next button we need to save our data in key-value format. Please check the below snapshot.

After clicking on the save button, we need to provide secret key name and description. Please check the below snapshot.

Step 3

Now we need to read the keys by programming. First, we have to Install AWS SDK for .Net & AWS Caching NuGet packages.

Now the question is, what is the use of cache?

After the first successful request, the secrets will be cached locally, which can be updated as required. Caching helps in improving performance as well as reducing billing.

Please check the below code snippets to access secret key manager data.

// Calling Secret key Manager with Secret Name.
AmazonSecretsManagerClient client = new AmazonSecretsManagerClient();
var secretRequest = new GetSecretValueRequest {
    SecretId = secretName,
        VersionStage = "AWSCURRENT"
};
GetSecretValueResponse response = null;
response = client.GetSecretValueAsync(secretRequest).Result;
cache = new SecretsManagerCache(client);
// Ends here.
// Reading the key's Via cache 
Keys = cache.GetSecretString(secretName).Result;

Summary

In this blog, we learned about AWS secret key manager creation and accessing the data programmatically.

I hope that you find it helpful. Eat->Code->Sleep->Repeat.