代码之家  ›  专栏  ›  技术社区  ›  Sam

从azure function应用程序检索主机密钥

  •  10
  • Sam  · 技术社区  · 7 年前

    我正在尝试使用Azure cli编写环境脚本。我已经创建了一些功能应用程序,并希望添加一个主机密钥或至少检索自动创建的默认密钥。azure cli对此完全不支持。

    https://github.com/Azure/azure-webjobs-sdk-script/wiki/Key-management-API

    如: https://example-functions.azurewebsites.net/admin/host/keys?code=somecodeyoualreadyknow

    我看到了其他一些使用webapps scm api下载包含密钥的json文件的示例,但是我不确定如何使用该api进行身份验证。我有一个服务主体(userid、password、tenantid),我希望不必在脚本中添加另一个身份验证方案。

    7 回复  |  直到 7 年前
        1
  •  9
  •   James McShane    5 年前

    我刚刚能够使用以下命令在Azure CLI上实现这一点:

    az rest --method post --uri \
    "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Web/sites/$FUNCTION_APP_NAME/host/default/listKeys?api-version=2018-11-01" \
    --query functionKeys.default --output tsv
    

        2
  •  8
  •   Mike S    7 年前

    以下是步骤。

    1. 假设您已经拥有Kudu部署凭据。(听起来你已经知道该怎么做了。你可以通过你的服务负责人打电话等方式获得)
    2. 从函数API中,您可以获得所有密钥(包括主密钥)。

    # You need to start with these:
    $site = "YourSiteName"
    $username='YourDeploymentUserName'
    $password='YourDeploymentPassword'
    
    # Now... 
    $apiBaseUrl = "https://$($site).scm.azurewebsites.net/api"
    $siteBaseUrl = "https://$($site).azurewebsites.net"
    
    # For authenticating to Kudu
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
    
    
    # Call Kudu /api/functions/admin/token to get a JWT that can be used with the Functions Key API 
    $jwt = Invoke-RestMethod -Uri "$apiBaseUrl/functions/admin/token" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET
    
    # Call Functions Key API to get the master key 
    $x = Invoke-RestMethod -Uri "$siteBaseUrl/admin/host/systemkeys/_master" -Headers @{Authorization=("Bearer {0}" -f $jwt)} -Method GET
    
    $masterKey = $x.value
    
        3
  •  6
  •   Tom Sun    7 年前

    我不知道如何使用我的服务主体凭据获取“kudu”凭据

    如果C代码可以接受,我们可以使用 Microsoft.Azure.Management.ResourceManager.Fluent Microsoft.Azure.Management.Fluent 轻松做到这一点。下面是如何获取kudu凭据和运行密钥管理API的演示。我在本地测试它,它在我这边正常工作。

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

    enter image description here

        4
  •  4
  •   Gavin.G    4 年前

    Get-AzResource -Name RESOURCE-NAME | Invoke-AzResourceAction -Action host/default/listkeys -Force
    
        5
  •  0
  •   Sam    7 年前

    谢谢你们的回复。使用你的答案Mike S并翻阅csharp fluent源代码(感谢Tom Sun),我最终得到了这个。当然需要很多代币!我开始的凭据是你会从中得到的 az ad sp create-for-rbac -n $name --role contributor

    $credentials = (ConvertFrom-Json $env:AzureCliLogin)
    
    $tenant = $credentials.tenant
    $clientId = $credentials.appId
    $clientSecret = $credentials.password
    $subscriptionId = "<subscription id>"
    
    $body = @{
        "grant_type"="client_credentials";
        "client_id"=$clientId;
        "client_secret"=$clientSecret;
        "resource"="https://management.azure.com/"
    }
    
    $authInfo = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenant/oauth2/token" -Body $body -Method Post -Headers @{"Content-Type"="application/x-www-form-urlencoded"} 
    
    $publishData = Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Web/sites/$name/publishxml?api-version=2016-08-01" -Method Post -Headers @{"Authorization"="Bearer $($authInfo.access_token)"}
    
    $userName = $publishData.publishData.publishProfile[0].userName
    $password = $publishData.publishData.publishProfile[0].userPWD
    
    $apiBaseUrl = "https://$name.scm.azurewebsites.net/api"
    $siteBaseUrl = "https://$name.azurewebsites.net"
    
    # For authenticating to Kudu
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))    
    
    # Call Kudu /api/functions/admin/token to get a JWT that can be used with the Functions Key API 
    $jwt = Invoke-RestMethod -Uri "$apiBaseUrl/functions/admin/token" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET
    
    # Call Functions Key API to get the master key 
    $x = Invoke-RestMethod -Uri "$siteBaseUrl/admin/host/systemkeys/_master" -Headers @{Authorization=("Bearer {0}" -f $jwt)} -Method GET
    
    $masterKey = $x.value
    
        6
  •  0
  •   Flacito    6 年前

    如果要在bash中执行此操作,请参见 this gist

        7
  •  0
  •   David Peden    3 年前

    确保您拥有最新版本的Az模块。

    安装:

    Install-Module -Name Az -Force
    

    更新:

    Update-Module -Name Az
    

    请确保在运行上述命令之一后启动一个新的PowerShell窗口。

    $azureFunction = Get-AzFunctionApp -ResourceGroupName $resourceGroupName -Name $azureFunctionName
    $keys = Invoke-AzResourceAction -ResourceId $($azureFunction.Id) -Action "host/default/listKeys" -Force
    $defaultKey = $keys.functionKeys.default