简体   繁体   English

从我的azure函数中获取主机密钥

[英]Retreive the host key from within my azure function

To read an Application setting in Azure function I can do 要读取Azure功能中的应用程序设置,我可以执行

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 我喜欢根据他们使用的键来识别我的azure函数的调用方,但是讨厌在应用程序设置中拥有此键的副本

You could install Microsoft.Azure.Management.ResourceManager.Fluent and Microsoft.Azure.Management.Fluent to do that easily. 您可以安装Microsoft.Azure.Management.ResourceManager.FluentMicrosoft.Azure.Management.Fluent来轻松做到这一点。 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. 以下是演示如何获取kudu凭据并运行密钥管理API的演示。我在本地对其进行了测试,它可以正常运行。

For more detail, you could refer to this SO thread with C# code or use powershell to get it. 有关更多详细信息,您可以使用C#代码引用此SO线程 ,或使用powershell进行获取。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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