教程:使用 Windows VM 系统分配的托管标识访问 Azure Cosmos DBTutorial: Use a Windows VM system-assigned managed identity to access Azure Cosmos DB

Azure 资源的托管标识是 Azure Active Directory 的一项功能。Managed identities for Azure resources is a feature of Azure Active Directory. 支持 Azure 资源的托管标识的每个 Azure 服务都受其自己的时间线限制。Each of the Azure services that support managed identities for Azure resources are subject to their own timeline. 在开始之前,请务必查看资源的托管标识的可用性状态以及已知问题Make sure you review the availability status of managed identities for your resource and known issues before you begin.

本教程介绍了如何使用 Windows 虚拟机 (VM) 的系统分配托管标识来访问 Cosmos DB。This tutorial shows you how to use a system-assigned managed identity for a Windows virtual machine (VM) to access Cosmos DB. 你将学习如何执行以下操作:You learn how to:

  • 创建 Cosmos DB 帐户Create a Cosmos DB account
  • 向 Windows VM 系统分配的托管标识授予对 Cosmos DB 帐户访问密钥的访问权限Grant a Windows VM system-assigned managed identity access to the Cosmos DB account access keys
  • 使用 Windows VM 系统分配的托管标识获取访问令牌来调用 Azure 资源管理器Get an access token using the Windows VM system-assigned managed identity to call Azure Resource Manager
  • 从 Azure 资源管理器中获取访问密钥,以便进行 Cosmos DB 调用Get access keys from Azure Resource Manager to make Cosmos DB calls

先决条件Prerequisites

启用Enable

启用系统分配的托管标识只需单击一次即可。Enabling a system-assigned managed identity is a one-click experience. 可以在创建 VM 的过程中或在现有 VM 的属性中启用它。You can either enable it during the creation of a VM or in the properties of an existing VM.

新建存储帐户

若要在新 VM 上启用系统分配的托管标识,请执行以下操作:To enable a system-assigned managed identity on a new VM:

  1. 登录到 Azure 门户Sign in to Azure portal

  2. 创建启用了系统分配标识的虚拟机Create a virtual machine with system-assigned identity enabled

授予访问权限Grant access

创建 Cosmos DB 帐户Create a Cosmos DB account

如果还没有 Cosmos DB 帐户,请创建一个。If you don't already have one, create a Cosmos DB account. 可以跳过此步骤,使用现有的 Cosmos DB 帐户。You can skip this step and use an existing Cosmos DB account.

  1. 单击 Azure 门户左上角的“+/创建新服务”按钮。 Click the +/Create new service button found on the upper left-hand corner of the Azure portal.
  2. 单击“数据库”,然后单击“Azure Cosmos DB”,新的“新建帐户”面板便会显示。 Click Databases, then Azure Cosmos DB, and a new "New account" panel displays.
  3. 输入 Cosmos DB 帐户的 ID,供以后使用。Enter an ID for the Cosmos DB account, which you use later.
  4. API 应设置为“SQL”。API should be set to "SQL." 本教程中介绍的方法可以与其他可用的 API 类型配合使用,但本教程中的步骤是针对 SQL API 的。The approach described in this tutorial can be used with the other available API types, but the steps in this tutorial are for the SQL API.
  5. 确保“订阅”和“资源组”与上一步中创建 VM 时指定的名称匹配。 Ensure the Subscription and Resource Group match the ones you specified when you created your VM in the previous step. 选择提供 Cosmos DB 的“位置”。 Select a Location where Cosmos DB is available.
  6. 单击创建Click Create.

创建集合Create a collection

接下来,在 Cosmos DB 帐户中添加数据集合,以便在后续步骤中进行查询。Next, add a data collection in the Cosmos DB account that you can query in later steps.

  1. 导航到新创建的 Cosmos DB 帐户。Navigate to your newly created Cosmos DB account.
  2. 在“概览”选项卡中单击“+/添加集合”按钮,此时“添加集合”面板就会滑出。 On the Overview tab click the +/Add Collection button, and an "Add Collection" panel slides out.
  3. 为集合提供数据库 ID、集合 ID,选择存储容量,输入分区键,输入吞吐量值,然后单击“确定”。 Give the collection a database ID, collection ID, select a storage capacity, enter a partition key, enter a throughput value, then click OK. 就本教程来说,使用“测试”作为数据库 ID 和集合 ID,选择固定的存储容量和最低吞吐量(400 RU/秒)就可以了。For this tutorial, it is sufficient to use "Test" as the database ID and collection ID, select a fixed storage capacity and lowest throughput (400 RU/s).

授予访问 Cosmos DB 帐户访问密钥的权限Grant access to the Cosmos DB account access keys

本部分介绍如何授予 Windows VM 系统分配的托管标识访问 Cosmos DB 帐户访问密钥的权限。This section shows how to grant Windows VM system-assigned managed identity access to the Cosmos DB account access keys. Cosmos DB 原本不支持 Azure AD 身份验证。Cosmos DB does not natively support Azure AD authentication. 但是,可以使用系统分配的托管标识从资源管理器检索 Cosmos DB 访问密钥,然后使用该密钥访问 Cosmos DB。However, you can use a system-assigned managed identity to retrieve a Cosmos DB access key from the Resource Manager, and use the key to access Cosmos DB. 在此步骤中,将向 Windows VM 系统分配的托管标识授予对 Cosmos DB 帐户密钥的访问权限。In this step, you grant your Windows VM system-assigned managed identity access to the keys to the Cosmos DB account.

若要向 Windows VM 系统分配的托管标识授予在 Azure 资源管理器中使用 PowerShell 访问 Cosmos DB 帐户的权限,请更新环境的 <SUBSCRIPTION ID><RESOURCE GROUP><COSMOS DB ACCOUNT NAME> 的值。To grant the Windows VM system-assigned managed identity access to the Cosmos DB account in Azure Resource Manager using PowerShell, update the values for <SUBSCRIPTION ID>, <RESOURCE GROUP>, and <COSMOS DB ACCOUNT NAME> for your environment. Cosmos DB 在使用访问密钥时支持两种级别的粒度:对帐户的读/写访问权限,以及对帐户的只读访问权限。Cosmos DB supports two levels of granularity when using access keys: read/write access to the account, and read-only access to the account. 如果需要获取帐户的读/写密钥,请分配 DocumentDB Account Contributor 角色;如果需要获取帐户的只读密钥,请分配 Cosmos DB Account Reader Role 角色。Assign the DocumentDB Account Contributor role if you want to get read/write keys for the account, or assign the Cosmos DB Account Reader Role role if you want to get read-only keys for the account. 对于本教程,请分配 Cosmos DB Account Reader RoleFor this tutorial, assign the Cosmos DB Account Reader Role:

$spID = (Get-AzVM -ResourceGroupName myRG -Name myVM).identity.principalid
New-AzRoleAssignment -ObjectId $spID -RoleDefinitionName "Cosmos DB Account Reader Role" -Scope "/subscriptions/<mySubscriptionID>/resourceGroups/<myResourceGroup>/providers/Microsoft.DocumentDb/databaseAccounts/<COSMOS DB ACCOUNT NAME>"

访问数据Access data

本部分介绍如何使用 Windows VM 系统分配的托管标识的访问令牌调用 Azure 资源管理器。This section shows how to call Azure Resource Manager using an access token for the Windows VM system-assigned managed identity. 在本教程的剩余部分中,我们从先前创建的 VM 入手。For the remainder of the tutorial, we will work from the VM we created earlier.

需在 Windows VM 上安装最新版本的 Azure CLIYou need to install the latest version of Azure CLI on your Windows VM.

获取访问令牌Get an access token

  1. 在 Azure 门户中,导航到“虚拟机” ,转到 Windows 虚拟机,然后在“概述” 页中单击顶部的“连接” 。In the Azure portal, navigate to Virtual Machines, go to your Windows virtual machine, then from the Overview page click Connect at the top.

  2. 输入创建 Windows VM 时添加的用户名 和密码 。Enter in your Username and Password for which you added when you created the Windows VM.

  3. 现在,已经创建了与虚拟机的远程桌面连接 ,请在远程会话中打开 PowerShell。Now that you have created a Remote Desktop Connection with the virtual machine, open PowerShell in the remote session.

  4. 使用 Powershell 的 Invoke-WebRequest,向 Azure 资源终结点的本地托管标识发出请求以获取 Azure 资源管理器的访问令牌。Using Powershell’s Invoke-WebRequest, make a request to the local managed identities for Azure resources endpoint to get an access token for Azure Resource Manager.

    $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.chinacloudapi.cn%2F' -Method GET -Headers @{Metadata="true"}
    

    Note

    “资源”参数的值必须完全匹配 Azure AD 预期的值。The value of the "resource" parameter must be an exact match for what is expected by Azure AD. 如果使用 Azure 资源管理器资源 ID,必须在 URI 的结尾添加斜线。When using the Azure Resource Manager resource ID, you must include the trailing slash on the URI.

    接下来,提取“内容”元素,该元素以 JavaScript 对象表示法 (JSON) 格式字符串的形式存储在 $response 对象中。Next, extract the "Content" element, which is stored as a JavaScript Object Notation (JSON) formatted string in the $response object.

    $content = $response.Content | ConvertFrom-Json
    

    接下来,从响应中提取访问令牌。Next, extract the access token from the response.

    $ArmToken = $content.access_token
    

获取访问密钥Get access keys

本部分介绍如何从 Azure 资源管理器获取访问密钥以进行 Cosmos DB 调用。This section shows how to get access keys from Azure Resource Manager to make Cosmos DB calls. 现在,请使用在上一部分检索到的访问令牌通过 PowerShell 调用资源管理器,以便检索 Cosmos DB 帐户访问密钥。Now use PowerShell to call Resource Manager using the access token retrieved in the previous section to retrieve the Cosmos DB account access key. 有了访问密钥以后,即可查询 Cosmos DB。Once we have the access key, we can query Cosmos DB. 请务必将 <SUBSCRIPTION ID><RESOURCE GROUP><COSMOS DB ACCOUNT NAME> 参数值替换为你自己的值。Be sure to replace the <SUBSCRIPTION ID>, <RESOURCE GROUP>, and <COSMOS DB ACCOUNT NAME> parameter values with your own values. <ACCESS TOKEN> 值替换为前面检索到的访问令牌。Replace the <ACCESS TOKEN> value with the access token you retrieved earlier. 若要检索读/写密钥,请使用密钥操作类型 listKeysIf you want to retrieve read/write keys, use key operation type listKeys. 若要检索只读密钥,请使用密钥操作类型 readonlykeysIf you want to retrieve read-only keys, use the key operation type readonlykeys:

Invoke-WebRequest -Uri 'https://management.chinacloudapi.cn/subscriptions/<SUBSCRIPTION-ID>/resourceGroups/<RESOURCE-GROUP>/providers/Microsoft.DocumentDb/databaseAccounts/<COSMOS DB ACCOUNT NAME>/listKeys/?api-version=2016-03-31' -Method POST -Headers @{Authorization="Bearer $ARMToken"}

响应提供一个密钥列表。The response give you the list of Keys. 例如,如果获取只读密钥:For example, if you get read-only keys:

{"primaryReadonlyMasterKey":"bWpDxS...dzQ==",
"secondaryReadonlyMasterKey":"38v5ns...7bA=="}

有了 Cosmos DB 帐户的访问密钥以后,即可将其传递给 Cosmos DB SDK 并通过调用来访问该帐户。 如需快速示例,可将该访问密钥传递给 Azure CLI。 在 Azure 门户中,可以从 Cosmos DB 帐户边栏选项卡上的“概览”选项卡获取 <COSMOS DB CONNECTION URL><ACCESS KEY> 替换为在上面获取的值:Replace the <ACCESS KEY> with the value you obtained above:

az cosmosdb collection show -c <COLLECTION ID> -d <DATABASE ID> --url-connection "<COSMOS DB CONNECTION URL>" --key <ACCESS KEY>

此 CLI 命令返回有关集合的详细信息:This CLI command returns details about the collection:

{
  "collection": {
    "_conflicts": "conflicts/",
    "_docs": "docs/",
    "_etag": "\"00006700-0000-0000-0000-5a8271e90000\"",
    "_rid": "Es5SAM2FDwA=",
    "_self": "dbs/Es5SAA==/colls/Es5SAM2FDwA=/",
    "_sprocs": "sprocs/",
    "_triggers": "triggers/",
    "_ts": 1518498281,
    "_udfs": "udfs/",
    "id": "Test",
    "indexingPolicy": {
      "automatic": true,
      "excludedPaths": [],
      "includedPaths": [
        {
          "indexes": [
            {
              "dataType": "Number",
              "kind": "Range",
              "precision": -1
            },
            {
              "dataType": "String",
              "kind": "Range",
              "precision": -1
            },
            {
              "dataType": "Point",
              "kind": "Spatial"
            }
          ],
          "path": "/*"
        }
      ],
      "indexingMode": "consistent"
    }
  },
  "offer": {
    "_etag": "\"00006800-0000-0000-0000-5a8271ea0000\"",
    "_rid": "f4V+",
    "_self": "offers/f4V+/",
    "_ts": 1518498282,
    "content": {
      "offerIsRUPerMinuteThroughputEnabled": false,
      "offerThroughput": 400
    },
    "id": "f4V+",
    "offerResourceId": "Es5SAM2FDwA=",
    "offerType": "Invalid",
    "offerVersion": "V2",
    "resource": "dbs/Es5SAA==/colls/Es5SAM2FDwA=/"
  }
}

禁用Disable

若要在 VM 上禁用系统分配的标识,请将系统分配的标识的状态设为“关” 。To disable the system-assigned identity on your VM, set the status of the system-assigned identity to Off.

新建存储帐户

后续步骤Next steps

在本教程中,你学习了如何使用 Windows VM 系统分配的标识来访问 Cosmos DB。In this tutorial, you learned how to use a Windows VM system-assigned identity to access Cosmos DB. 若要详细了解 Cosmos DB,请参阅:To learn more about Cosmos DB see: