Azure功能:如何使用C#代码以编程方式访问主机密钥?

时间:2019-09-25 15:41:47

标签: c# azure-functions azure-function-app

我正在编写一个Azure Function App,该App需要提供带有表单的HTML页面。该表格应发回到应用程序的一个端点。该应用程序应使用Azure的Authorization Key功能进行保护。

Azure允许呼叫者以两种方式提供其密钥:

  1. 带有code请求查询参数。
  2. 带有x-functions-clientid HTTP标头。

要成功调用Azure Function App的另一个终结点,我将需要在请求中提供主机密钥。例如这样的

    <form method='post' action='DoSomething?code={{{WHERE TO GET THIS FROM?}}}'>
        <input name='someInput' />
        <input type='submit' />
    </form>

我正在使用C#生成HTML代码。以编程方式获取主机密钥的最防弹方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用Microsoft.Azure.Management.ResourceManager.Fluent和Microsoft.Azure.Management.Fluent来执行此操作。

请参阅此SO thread,以获取更多信息。

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;
  }