Accessing Connection String values in Azure Function V1 and V2

Connection string is a good way to store database or source system connection string. Currently Azure Function provides four different types on connection strings as below.

  1. MySql- Conection string for MySql database
  2. SQLServer- Connection strings for SQL server
  3. SQLAzure – Connection strings for SQL Azure
  4. Custom—Any other types of connection string excluding above

The way for accessing Connection string is different in V1 and V2 as V2 is does not support configuration manager.

Accessing Connection string in Azure function V1

Below are the steps for accessing connection string in azure function v1 .

  1. Add nuget package “Configuration.ConfigurationManager
  2. Add the namespace “System.Configuration
  3. Then access connection string as below
var connectionString = ConfigurationManager.ConnectionStrings[“CRM_CONNECTION_STRING”].ConnectionString;

While running the code from azure app service create the connection as custom connection string

The sample code could be found on GitHub

 Accessing Connection string in Azure function V2

Unlike azure function 1.x azure function 2.x does not support configuration manager. So, the process for accessing the connection string is different. Below are the steps for that

  1. Add the namespace “Extensions.Configuration
  2. Add a third parameter in the function Run method of type ExecutionContext
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, “get”, “post”, Route = null)]HttpRequest req, ILogger log, ExecutionContext context)
  1. Add the following code in the beginning of the function
var config = new ConfigurationBuilder()

.SetBasePath(context.FunctionAppDirectory)

.AddJsonFile(“local.settings.json”, optional: true, reloadOnChange: true)

.AddEnvironmentVariables()

.Build();

For a local run this code will get application settings and connection string from local.settings.json and for a deployment this code this take the environment variables from appsettings and connection string from the app service.

  1. Access Connection String as below
var connectionString = config.GetConnectionString(“CRM_CONNECTION_STRING”);
  1. Access app settings as below
var setting1 = config[“Settings1”];

The sample code can be found on GitHub

 

 

 

 

 

 

 

Advertisements

Accessing Key Vault in Azure Function

Azure Key Vault is a secure storage for keys connection strings and password. Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. By using Key Vault, you can encrypt keys and secrets (such as authentication keys, storage account keys, data encryption keys, .PFX files, and passwords) using keys protected by hardware security modules (HSMs).

Key Vault streamlines the key management process and enables you to maintain control of keys that access and encrypt your data. Developers can create keys for development and testing in minutes, and then seamlessly migrate them to production keys. Security administrators can grant (and revoke) permission to keys, as needed. More details about this can be found on https://docs.microsoft.com/en-us/azure/key-vault/key-vault-whatis

Below I will be discussing what all are the steps to access Key vault from Azure function.

Steps to Access key vault

  • Create an Azure Key vault as below

1

  • Create a key vault secret as below

2

3

  • Write an Azure Function code as below
[FunctionName(“GetKeyVaultValues”)]

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, “get”, “post”, Route = null)]HttpRequestMessage req, TraceWriter log)

{

log.Info(“C# HTTP trigger function processed a request.”);

string linkKeyVaultUrl = $”https://keyvaultaccess.vault.azure.net/secrets/&#8221;;

string keyvaultKey = $”KeyVaultKey”;

var secretURL = linkKeyVaultUrl + keyvaultKey;

 

var azureServiceTokenProvider = new AzureServiceTokenProvider();

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

try

{

var clientIdRecord = await kvClient.GetSecretAsync(secretURL).ConfigureAwait(false);

string KeyvaultValue = clientIdRecord.Value;

return req.CreateErrorResponse(HttpStatusCode.OK, “Key vault secret value is  :  ” + KeyvaultValue);

}

catch (System.Exception ex)

{

 

return req.CreateResponse(HttpStatusCode.BadRequest, “Key vault value request is not successfull”);

}

}

  • The nuget packages used in this code are as follows
    • Microsoft.Azure.KeyVault
    • Microsoft.Azure.Services.AppAuthentication
  • publish the Azure function as below

4

  • Go to the platform feature for the application and set the managed identity as On

5

  • Go to the Azure Key Vault
  • Add the application to access policy as shown below.

6

 

7

  • Set the Key and Secret permission as below

8

Now you can go to “Postman” and call the method to get the key vault value and use wherever required

9