1

To read an Application setting in Azure function I can do

Environment.GetEnvironmentVariable("MyVariable", EnvironmentVariableTarget.Process);

Is it possible to get a Host key in a similar way? I like to identify the caller of my azure function based on the key they are using but hate to have a copy of this key in Application settings

Jepzen
  • 2,942
  • 6
  • 40
  • 62

1 Answers1

0

You could install Microsoft.Azure.Management.ResourceManager.Fluent and Microsoft.Azure.Management.Fluent to do that easily. The following is the demo that how to get kudu credentials and run Key management API .I test it locally, it works correctly on my side.

For more detail, you could refer to this SO thread with C# code or use powershell to get it.

string clientId = "client id";
 string secret = "secret key";
 string tenant = "tenant id";
 var functionName ="functionName";
 var webFunctionAppName = "functionApp name";
 string resourceGroup = "resource group name";
 var credentials = new AzureCredentials(new ServicePrincipalLoginInformation { ClientId = clientId, ClientSecret = secret}, tenant, AzureEnvironment.AzureGlobalCloud);
 var azure = Azure
          .Configure()
          .Authenticate(credentials)
          .WithDefaultSubscription();

 var webFunctionApp = azure.AppServices.FunctionApps.GetByResourceGroup(resourceGroup, webFunctionAppName);
 var ftpUsername = webFunctionApp.GetPublishingProfile().FtpUsername;
 var username = ftpUsername.Split('\\').ToList()[1];
 var password = webFunctionApp.GetPublishingProfile().FtpPassword;
 var base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{password}"));
 var apiUrl = new Uri($"https://{webFunctionAppName}.scm.azurewebsites.net/api");
 var siteUrl = new Uri($"https://{webFunctionAppName}.azurewebsites.net");
 string JWT;
 using (var client = new HttpClient())
  {
     client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Auth}");

     var result = client.GetAsync($"{apiUrl}/functions/admin/token").Result;
     JWT = result.Content.ReadAsStringAsync().Result.Trim('"'); //get  JWT for call funtion key
   }
 using (var client = new HttpClient())
 {
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + JWT);
    var key = client.GetAsync($"{siteUrl}/admin/functions/{functionName}/keys").Result.Content.ReadAsStringAsync().Result;
  }

The output: enter image description here

Joey Cai
  • 18,968
  • 1
  • 20
  • 30
  • Did you read this update? I understand it as this solution will stop working since the keys will be moved to Blob Storage ? – Jepzen Sep 05 '18 at 08:50
  • Since update 2.0.12050 de keys are no longer stored as a storage file but in a blob-container. A (temporary?) solution is to restore the location of the secrets by changing App Setting **AzureWebJobsSecretStorageType** to **files**. see also https://aka.ms/funcsecrets – TJ Galama Oct 11 '18 at 07:13