使用C#从Azure中的授权密钥功能级别授权中检索密钥

时间:2019-02-26 06:17:01

标签: c# azure key-management

我需要通过代码而不是通过门户网站来获取密钥。为此,我在Google中找到了REST API。 这是到Azure Key management API的链接,但是要做到这一点,我们需要进行身份验证。

我们必须仅使用C#开发所有这些。

1 个答案:

答案 0 :(得分:0)

关于此问题,请参考以下代码。

 #install Microsoft.Azure.Management.ResourceManager.Fluent and Microsoft.Azure.Management.Fluent    
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;
      }

此外,您还可以参考document