在没有 PowerShell 的情况下在 Azure Key Vault 中设置密钥

Setting keys in Azure Key Vault without PowerShell

如何在不使用 PowerShell 的情况下在 Azure Key Vault 中设置机密。我们正在使用 Azure Key Vault 来安全地存储连接字符串和其他一些应用程序机密。我们可以使用 PowerShell 脚本添加机密,但我想知道是否有另一种方法可以在 Azure KeyVault 中添加密钥,最好是使用 API。我们实际上需要提供一个管理工具,应用程序管理员可以使用该工具 add/modify 密钥库中的秘密。

Microsoft 确实为此提供了 REST API。你可以查看一下here.

下面是一个 PowerShell 脚本,向您展示了如何使用 API 创建密钥。

Add-Type -Path 'C:\Program Files\Microsoft Azure Active Directory Connect\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'

$tenantID = "<your tenant ID>"
$loginEndpoint = "https://login.windows.net/"

# the common redirect URI and client ID
$redirectURI = New-Object System.Uri ("urn:ietf:wg:oauth:2.0:oob")
$clientID = "1950a258-227b-4e31-a9cf-717495945fc2"

$resource = "https://vault.azure.net"

$authString = $loginEndpoint + $tenantID

$authenticationContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ($authString, $false)

$promptBehaviour = [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto

$userIdentifierType = [Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType]::RequiredDisplayableId

$userIdentifier = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier ("<your Azure account>", $userIdentifierType)

$authenticationResult = $authenticationContext.AcquireToken($resource, $clientID, $redirectURI, $promptBehaviour, $userIdentifier); 

# construct authorization header for the REST API.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
$headers = @{"Authorization"=$authHeader; "Content-Type"="application/json"}

$key = Invoke-RestMethod -Method POST -Uri "https://<your key vault>.vault.azure.net/keys/<key name>/create?api-version=2015-06-01" -Headers $headers -Body '{"kty": "RSA","attributes": {"enabled": true}}'

我不知道你用的是什么编程语言,所以我用的是PowerShell,因为它很容易测试。该脚本是从 C# 代码转换而来的,因此可以轻松地转换回 C#。如果您不喜欢提示行为,您可以使用带有安全字符串的凭据。对于其他编程语言,可以使用相应的ADAL。如果 ADAL 不适用于该编程语言,您可以使用 OAuth2。

您现在可以通过 Azure 门户添加密钥和机密,而无需使用 PowerShell。

这个问题很老了,我想我会为遇到它的人增加一个新的角度)...

您现在还可以使用 ARM 模板存储机密,您已经可以使用一段时间了,但是要找到相关文档在很大程度上非常困难(我第一次找到它时花了一些时间才找到!) ,但这是 azure 快速入门模板中的一个方便示例:

https://github.com/Azure/azure-quickstart-templates/blob/master/201-key-vault-secret-create/azuredeploy.json

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "keyVaultName": {
      "type": "string",
      "metadata": {
        "description": "Name of the Key Vault"
      }
    },
    "tenantId": {
      "type": "string",
      "metadata": {
        "description": "Tenant Id for the subscription and use assigned access to the vault. Available from the Get-AzureRMSubscription PowerShell cmdlet"
      }
    },
    "accessPolicies": {
      "type": "array",
      "defaultValue": "{}",
      "metadata": {
        "description": "Access policies object {\"tenantId\":\"\",\"objectId\":\"\",\"permissions\":{\"keys\":[\"\"],\"secrets\":[\"\"]}}"
      }
    },
    "vaultSku": {
      "type": "string",
      "defaultValue": "Standard",
      "allowedValues": [
        "Standard",
        "Premium"
      ],
      "metadata": {
        "description": "SKU for the vault"
      }
    },
    "enabledForDeployment": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies if the vault is enabled for VM or Service Fabric deployment"
      }
    },
    "enabledForTemplateDeployment": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies if the vault is enabled for ARM template deployment"
      }
    },
    "enableVaultForVolumeEncryption": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies if the vault is enabled for volume encryption"
      }
    },
    "secretsObject": {
      "type": "secureObject",
      "defaultValue": "{}",
      "metadata": {
        "description": "all secrets {\"secretName\":\"\",\"secretValue\":\"\"} wrapped in a secure object"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.KeyVault/vaults",
      "name": "[parameters('keyVaultName')]",
      "apiVersion": "2015-06-01",
      "location": "[parameters('location')]",
      "tags": {
        "displayName": "KeyVault"
      },
      "properties": {
        "enabledForDeployment": "[parameters('enabledForDeployment')]",
        "enabledForTemplateDeployment": "[parameters('enabledForTemplateDeployment')]",
        "enabledForVolumeEncryption": "[parameters('enableVaultForVolumeEncryption')]",
        "tenantId": "[parameters('tenantId')]",
        "accessPolicies": "[parameters('accessPolicies')]",
        "sku": {
          "name": "[parameters('vaultSku')]",
          "family": "A"
        }
      }
    },
    {
      "type": "Microsoft.KeyVault/vaults/secrets",
      "name": "[concat(parameters('keyVaultName'), '/', parameters('secretsObject').secrets[copyIndex()].secretName)]",
      "apiVersion": "2015-06-01",
      "properties": {
        "value": "[parameters('secretsObject').secrets[copyIndex()].secretValue]"
      },
      "dependsOn": [
        "[concat('Microsoft.KeyVault/vaults/', parameters('keyVaultName'))]"
      ],
      "copy": {
        "name": "secretsCopy",
        "count": "[length(parameters('secretsObject').secrets)]"
      }
    }
  ]
}