简体   繁体   中英

Retreive the host key from within my azure function

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

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: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM