共用方式為


使用角色型存取控制和 Microsoft Entra ID 連線到適用於 NoSQL 的 Azure Cosmos DB

角色型存取控制是指管理 Azure 中資源存取權的方法。 此方法是以指派角色的特定身分為基礎,這些角色會管理他們對一或多個資源的存取層級。 角色型存取控制提供彈性的精細存取管理系統,確保身分識別僅具有執行任務所需的最低權限層級。

如需詳細資訊,請參閱 角色型存取控制

先決條件

  • 具有有效訂閱的 Azure 帳戶。 免費建立帳戶

  • 現有的 Azure Cosmos DB for NoSQL 帳戶。

  • Microsoft Entra ID 中的一或多個現有身分識別。

停用金鑰型驗證

停用金鑰型授權可防止在沒有更安全的 Microsoft Entra ID 驗證方法的情況下使用您的帳戶。 此程序是應在安全工作負載中的新帳戶上執行的步驟。 或者,在移轉至安全工作負載模式的現有帳戶上執行此程序。

首先,停用現有帳戶的金鑰型驗證,讓應用程式必須使用 Microsoft Entra ID 驗證。 請用 az resource update 來修改 properties.disableLocalAuth 已存在的用戶帳戶。

az resource update \
    --resource-group "<name-of-existing-resource-group>" \
    --name "<name-of-existing-account>" \
    --resource-type "Microsoft.DocumentDB/databaseAccounts" \
    --set properties.disableLocalAuth=true

首先,建立已停用金鑰型驗證的新帳戶,讓應用程式必須使用 Microsoft Entra 驗證。

  1. 建立新的 Bicep 檔案,以部署已停用金鑰型驗證的新帳戶。 將檔案命名為 deploy-new-account.bicep

    metadata description = 'Deploys a new Azure Cosmos DB account with key-based auth disabled.'
    
    @description('Name of the Azure Cosmos DB account.')
    param name string = 'csms-${uniqueString(resourceGroup().id)}'
    
    @description('Primary location for the Azure Cosmos DB account.')
    param location string = resourceGroup().location
    
    resource account 'Microsoft.DocumentDB/databaseAccounts@2024-05-15' = {
      name: name
      location: location
      kind: 'GlobalDocumentDB'
      properties: {
        databaseAccountOfferType: 'Standard'
        locations: [
          {
            locationName: location
          }
        ]
        disableLocalAuth: true
      }
    }
    
  2. az deployment group create 來使用新帳戶部署 Bicep 檔案。

    az deployment group create \
        --resource-group "<name-of-existing-resource-group>" \
        --template-file deploy-new-account.bicep
    

首先,停用現有帳戶的金鑰型驗證,讓應用程式必須使用 Microsoft Entra 驗證。 使用 Get-AzResourceSet-AzResource 分別讀取和更新現有帳戶。

$parameters = @{
    ResourceGroupName = "<name-of-existing-resource-group>"
    ResourceName = "<name-of-existing-account>"
    ResourceType = "Microsoft.DocumentDB/databaseAccounts"
}
$resource = Get-AzResource @parameters

$resource.Properties.DisableLocalAuth = $true

$resource | Set-AzResource -Force

使用下列步驟來建立新的 Azure Cosmos DB for NoSQL 帳戶,並停用金鑰型驗證,讓應用程式只需要使用 Microsoft Entra 驗證。

  1. 設定新的適用於 NoSQL 的 Azure Cosmos DB 帳戶時,請流覽至帳戶建立程式的 [ 安全性 ] 區段。

  2. 然後,針對金鑰型驗證選項選取停用

    在 Azure 入口網站 中建立新帳戶時停用金鑰型驗證選項的螢幕擷取畫面。

這很重要

修改 Azure Cosmos DB 帳戶需要至少具有 Microsoft.DocumentDb/databaseAccounts/*/write 權限的 Azure 角色。 如需詳細資訊,請參閱 Azure Cosmos DB 的許可權

驗證金鑰型驗證是否已停用

若要驗證金鑰型存取是否已停用,請嘗試使用 Azure SDK 使用資源擁有者密碼認證 (ROPC) 連線到適用於 NoSQL 的 Azure Cosmos DB。 此嘗試應該會失敗。 如有必要,此處提供常見程式設計語言的程式碼範例。

using Microsoft.Azure.Cosmos;

string connectionString = "AccountEndpoint=<nosql-endpoint>;AccountKey=<key>;";

CosmosClient client = new(connectionString);
const { CosmosClient } = require('@azure/cosmos');

const connectionString = 'AccountEndpoint=<nosql-endpoint>;AccountKey=<key>;';

const client = new CosmosClient(connectionString);
import { CosmosClient } from '@azure/cosmos'

let connectionString: string = 'AccountEndpoint=<nosql-endpoint>;AccountKey=<key>;';

const client: CosmosClient = new CosmosClient(connectionString);
from azure.cosmos import CosmosClient

connection_string = "AccountEndpoint=<nosql-endpoint>;AccountKey=<key>;"

client = CosmosClient(connection_string)
package main

import (
    "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

const connectionString = "AccountEndpoint=<nosql-endpoint>;AccountKey=<key>;"

func main() {
    client, _ := azcosmos.NewClientFromConnectionString(connectionString, nil)
}
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;

public class NoSQL{
    public static void main(String[] args){
        CosmosClient client = new CosmosClientBuilder()
            .endpoint("<nosql-endpoint>")
            .key("<key>")
            .buildClient();
    }
}
use azure_data_cosmos::CosmosClient;

fn main() {
    let client = CosmosClient::new_with_access_key(
        "<account-endpoint>",
        "<account-key>",
        None,
    ).unwrap();

    let container = client.database_client("<database-name>").container_client("<container-name>");

    let response = container.read_item("<partition-key>", "<item-id>", None);
    tokio::runtime::Runtime::new().unwrap().block_on(response).unwrap();
}

授與控制平面角色型存取權

控制平面存取是指管理 Azure 服務資源而不管理資料的能力。 例如,Azure Cosmos DB 控制平面存取可能包含下列功能:

  • 讀取所有帳戶和資源中繼資料
  • 讀取並重新產生帳戶金鑰和連接字串
  • 執行帳戶備份和還原
  • 啟動和追蹤資料傳輸任務
  • 管理資料庫和容器
  • 修改帳戶屬性

這很重要

在 Azure Cosmos DB 中,您需要控制平面存取權,才能管理原生資料平面角色型存取控制定義和指派。 由於 Azure Cosmos DB 的資料平面角色型存取控制機制是原生的,因此您需要控制平面存取權才能建立定義和指派,並將其儲存為 Azure Cosmos DB 帳戶內的資源。

首先,您必須準備具有 actions 清單的角色定義,以授與管理 Azure Cosmos DB 中帳戶資源的存取權。 在本指南中,您將設定內建角色和自訂角色。 然後,將新定義的角色指派給身分識別,讓您的應用程式可以存取 Azure Cosmos DB 中的資源。

  1. 使用 az role definition list列出與您的 Azure Cosmos DB 帳戶相關聯的所有角色定義。

    az role definition list \
        --name "Cosmos DB Operator"
    
  2. 檢閱輸出,並找出名為 Cosmos DB 運算子的角色定義。 輸出包含屬性中 id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    [
      {
        "assignableScopes": [
          "/"
        ],
        "description": "Lets you manage Azure Cosmos DB accounts, but not access data in them. Prevents access to account keys and connection strings.",
        "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/providers/Microsoft.Authorization/roleDefinitions/230815da-be43-4aae-9cb4-875f7bd000aa",
        "name": "230815da-be43-4aae-9cb4-875f7bd000aa",
        "permissions": [
          {
            "actions": [
              "Microsoft.DocumentDb/databaseAccounts/*",
              "Microsoft.Insights/alertRules/*",
              "Microsoft.Authorization/*/read",
              "Microsoft.ResourceHealth/availabilityStatuses/read",
              "Microsoft.Resources/deployments/*",
              "Microsoft.Resources/subscriptions/resourceGroups/read",
              "Microsoft.Support/*",
              "Microsoft.Network/virtualNetworks/subnets/joinViaServiceEndpoint/action"
            ],
            "condition": null,
            "conditionVersion": null,
            "dataActions": [],
            "notActions": [
              "Microsoft.DocumentDB/databaseAccounts/dataTransferJobs/*",
              "Microsoft.DocumentDB/databaseAccounts/readonlyKeys/*",
              "Microsoft.DocumentDB/databaseAccounts/regenerateKey/*",
              "Microsoft.DocumentDB/databaseAccounts/listKeys/*",
              "Microsoft.DocumentDB/databaseAccounts/listConnectionStrings/*",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/write",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/delete",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments/write",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments/delete",
              "Microsoft.DocumentDB/databaseAccounts/mongodbRoleDefinitions/write",
              "Microsoft.DocumentDB/databaseAccounts/mongodbRoleDefinitions/delete",
              "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/write",
              "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/delete"
            ],
            "notDataActions": []
          }
        ],
        "roleName": "Cosmos DB Operator",
        "roleType": "BuiltInRole",
        "type": "Microsoft.Authorization/roleDefinitions",
      }
    ]
    

    備註

    在此範例中, id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/providers/Microsoft.Authorization/roleDefinitions/230815da-be43-4aae-9cb4-875f7bd000aa。 此範例使用虛構資料,您的識別碼將與此範例不同。 不過,識別碼 (230815da-be43-4aae-9cb4-875f7bd000aa) 在 Azure 中的所有角色定義中都是全域唯一的。

  3. az group show 來取得目前資源群組的中繼資料。

    az group show \
        --name "<name-of-existing-resource-group>"
    
  4. 觀察上一個命令的輸出。 記錄此資源群組的屬性值 id,因為此值需要在下一個步驟中使用。

    {
      "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example",
      "location": "westus",
      "name": "msdocs-identity-example",
      "type": "Microsoft.Resources/resourceGroups"
    }
    

    備註

    在此範例中, id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example。 此範例使用虛構資料,您的識別碼將與此範例不同。 此字串是輸出的截斷範例。

  5. 建立名為 role-definition.json的新 JSON 檔案。 在檔案中,建立此資源定義,並指定此處列出的值。 針對 AssignableScopes 清單,新增 id 上一個步驟中記錄的資源群組屬性。

    {
      "Name": "Azure Cosmos DB Control Plane Owner",
      "IsCustom": true,
      "Description": "Can perform all control plane actions for an Azure Cosmos DB account.",
      "Actions": [
        "Microsoft.DocumentDb/*"
      ],
      "AssignableScopes": [
        "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example"
      ]
    }
    

    備註

    此範例使用上一個步驟中記錄的 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example 值。 您的實際資源識別碼可能會有所不同。

  6. 建立新的角色定義使用az role definition create。 使用 role-definition.json 檔案作為引數的 --role-definition 輸入。

    az role definition create \
        --role-definition role-definition.json
    
  7. 檢閱定義建立指令的輸出。 輸出包含屬性中 id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    {
      "assignableScopes": [
        "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example"
      ],
      "description": "Can perform all control plane actions for an Azure Cosmos DB account.",
      "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleDefinitions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1",
      "name": "e4e4e4e4-ffff-aaaa-bbbb-c5c5c5c5c5c5",
      "permissions": [
        {
          "actions": [
            "Microsoft.DocumentDb/*"
          ]
        }
      ],
      "roleName": "Azure Cosmos DB Control Plane Owner",
      "roleType": "CustomRole"
    }
    

    備註

    在此範例中, id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleDefinitions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1。 此範例使用虛構資料,您的識別碼將與此範例不同。 為了清楚起見,此範例是從部署輸出的典型 JSON 子集。

  8. 使用 az group show 再次取得您目前資源群組的中繼資料。

    az group show \
        --name "<name-of-existing-resource-group>"
    
  9. 觀察上一個命令的輸出。 記錄此資源群組的屬性值 id,因為此值需要在下一個步驟中使用。

    {
      "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example",
      "location": "westus",
      "name": "msdocs-identity-example",
      "type": "Microsoft.Resources/resourceGroups"
    }
    

    備註

    在此範例中, id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example。 此範例使用虛構資料,您的識別碼將與此範例不同。 此字串是輸出的截斷範例。

  10. 使用az role assignment create指派新角色。 使用資源群組的識別碼作為--scope引數,角色的識別碼作為-role引數,將身分的唯一識別碼用於--assignee引數。

    az role assignment create \
        --assignee "<your-principal-identifier>" \
        --role "subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleDefinitions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1" \
        --scope "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example"
    

    備註

    在此範例命令中,已將 設定 scope 為上一個步驟範例中的虛構範例 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example 。 您的資源群組識別碼將與此範例不同。 role 已被設定為虛構 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleDefinitions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1。 同樣,您的角色識別碼將是不同的。

  11. 觀察命令的輸出。 輸出包括 id 屬性中指派的唯一識別碼。

    {
      "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleAssignments/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1",
      "name": "ffffffff-5555-6666-7777-aaaaaaaaaaaa",
      "principalId": "aaaaaaaa-bbbb-cccc-1111-222222222222",
      "resourceGroup": "msdocs-identity-example",
      "roleDefinitionId": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleDefinitions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1",
      "scope": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example",
      "type": "Microsoft.Authorization/roleAssignments"
    }
    

    備註

    在此範例中, id 屬性是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleAssignments/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1,這是另一個虛構的範例。

  12. 重複這些步驟,以從您要使用的任何其他身分識別授予存取帳戶之權利。

    小提示

    您可以對任意數量的身分重複這些步驟。 一般而言,這些步驟至少會重複,以允許開發人員使用其人類身分識別存取帳戶,並允許應用程式使用受控識別存取資料。

  1. 使用 az role definition list列出與您的 Azure Cosmos DB 帳戶相關聯的所有角色定義。

    az role definition list \
        --name "Cosmos DB Operator"
    
  2. 檢閱輸出,並找出名為 Cosmos DB 運算子的角色定義。 輸出包含屬性中 id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    [
      {
        "assignableScopes": [
          "/"
        ],
        "description": "Lets you manage Azure Cosmos DB accounts, but not access data in them. Prevents access to account keys and connection strings.",
        "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/providers/Microsoft.Authorization/roleDefinitions/230815da-be43-4aae-9cb4-875f7bd000aa",
        "name": "230815da-be43-4aae-9cb4-875f7bd000aa",
        "permissions": [
          {
            "actions": [
              "Microsoft.DocumentDb/databaseAccounts/*",
              "Microsoft.Insights/alertRules/*",
              "Microsoft.Authorization/*/read",
              "Microsoft.ResourceHealth/availabilityStatuses/read",
              "Microsoft.Resources/deployments/*",
              "Microsoft.Resources/subscriptions/resourceGroups/read",
              "Microsoft.Support/*",
              "Microsoft.Network/virtualNetworks/subnets/joinViaServiceEndpoint/action"
            ],
            "condition": null,
            "conditionVersion": null,
            "dataActions": [],
            "notActions": [
              "Microsoft.DocumentDB/databaseAccounts/dataTransferJobs/*",
              "Microsoft.DocumentDB/databaseAccounts/readonlyKeys/*",
              "Microsoft.DocumentDB/databaseAccounts/regenerateKey/*",
              "Microsoft.DocumentDB/databaseAccounts/listKeys/*",
              "Microsoft.DocumentDB/databaseAccounts/listConnectionStrings/*",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/write",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/delete",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments/write",
              "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments/delete",
              "Microsoft.DocumentDB/databaseAccounts/mongodbRoleDefinitions/write",
              "Microsoft.DocumentDB/databaseAccounts/mongodbRoleDefinitions/delete",
              "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/write",
              "Microsoft.DocumentDB/databaseAccounts/mongodbUserDefinitions/delete"
            ],
            "notDataActions": []
          }
        ],
        "roleName": "Cosmos DB Operator",
        "roleType": "BuiltInRole",
        "type": "Microsoft.Authorization/roleDefinitions",
      }
    ]
    

    備註

    在此範例中, id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/providers/Microsoft.Authorization/roleDefinitions/230815da-be43-4aae-9cb4-875f7bd000aa。 此範例使用虛構資料,您的識別碼將與此範例不同。 不過,識別碼 (230815da-be43-4aae-9cb4-875f7bd000aa) 在 Azure 中的所有角色定義中都是全域唯一的。

  3. 建立新的 Bicep 檔案來定義您的角色定義。 將檔案命名為 control-plane-role-definition.bicep。 將這些項目新增至 actions 定義:

    Description
    Microsoft.DocumentDb/* 啟用所有可能的動作。
    metadata description = 'Create RBAC definition for control plane access to Azure Cosmos DB.'
    
    @description('Name of the role definition.')
    param roleDefinitionName string = 'Azure Cosmos DB Control Plane Owner'
    
    @description('Description of the role definition.')
    param roleDefinitionDescription string = 'Can perform all control plane actions for an Azure Cosmos DB account.'
    
    resource definition 'Microsoft.Authorization/roleDefinitions@2022-04-01' = {
      name: guid(subscription().id, resourceGroup().id, roleDefinitionName)
      scope: resourceGroup()
      properties: {
        roleName: roleDefinitionName
        description: roleDefinitionDescription
        type: 'CustomRole'
        permissions: [
          {
            actions: [
              'Microsoft.DocumentDb/*'
            ]
          }
        ]
        assignableScopes: [
          resourceGroup().id
        ]
      }
    }
    
    output definitionId string = definition.id
    
  4. 使用 az deployment group create部署 Bicep 範本。 指定 Bicep 範本和 Azure 資源群組的名稱。

    az deployment group create \
        --resource-group "<name-of-existing-resource-group>" \
        --template-file control-plane-role-definition.bicep
    
  5. 查看部署結果。 輸出包含屬性中 properties.outputs.definitionId.value 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    {
      "properties": {
        "outputs": {
          "definitionId": {
            "type": "String",
            "value": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleDefinitions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1"
          }
        }
      }
    }
    

    備註

    在此範例中, id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleDefinitions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1。 此範例使用虛構資料,您的識別碼將與此範例不同。 為了清楚起見,此範例是從部署輸出的典型 JSON 子集。

  6. 建立新的 Bicep 檔案以定義您的角色指派。 將檔案命名為 control-plane-role-assignment.bicep

    metadata description = 'Assign RBAC role for control plane access to Azure Cosmos DB.'
    
    @description('Id of the role definition to assign to the targeted principal in the context of the account.')
    param roleDefinitionId string
    
    @description('Id of the identity/principal to assign this role in the context of the account.')
    param identityId string
    
    resource assignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
      name: guid(subscription().id, resourceGroup().id, roleDefinitionId, identityId)
      scope: resourceGroup()
      properties: {
        roleDefinitionId: roleDefinitionId
        principalId: identityId
      }
    }
    
  7. 建立名為 control-plane-role-assignment 的新 Bicep 參數檔案。bicepparam 在此參數檔案中;將先前記錄的角色定義識別碼指派給 roleDefinitionId 參數,並將身分的唯一識別碼指派給 identityId 參數。

    using './control-plane-role-assignment.bicep'
    
    param roleDefinitionId = '<id-of-new-role-definition>'
    param identityId = '<id-of-existing-identity>'
    
  8. 使用 az deployment group create 部署此 Bicep 範本。

    az deployment group create \
        --resource-group "<name-of-existing-resource-group>" \
        --parameters control-plane-role-assignment.bicepparam \
        --template-file control-plane-role-assignment.bicep
    
  9. 重複這些步驟,以從您要使用的任何其他身分識別授予存取帳戶之權利。

    小提示

    您可以對任意數量的身分重複這些步驟。 一般而言,這些步驟至少會重複,以允許開發人員使用其人類身分識別存取帳戶,並允許應用程式使用受控識別存取資料。

  1. 登入 Azure 入口網站 (https://portal.azure.com)。

  2. 在全域搜尋列中輸入 資源群組

    Azure 入口網站中全域搜尋列的螢幕擷取畫面。

  3. [服務] 中,選取 [資源群組]。

    在搜尋功能表中選取的「資源群組」選項的螢幕擷取畫面。

  4. [資源群組] 窗格中,選取您現有的資源群組。

    訂用帳戶資源群組清單中現有資源群組的螢幕擷取畫面。

    備註

    此範例螢幕擷取畫面包含 msdocs-identity-example 資源群組。 您的實際資源群組名稱可能不同。

  5. 在資源群組的窗格中,選取服務功能表中的存取控制 (IAM)。

    資源群組服務功能表中「存取控制 (IAM)」選項的螢幕擷取畫面。

  6. [存取控制 (IAM)] 窗格中,選取 [ 角色]。

    「存取控制 (IAM)」窗格中「角色」選項的螢幕擷取畫面。

  7. 在 [ 角色 ] 區段中,使用搜尋片語 Cosmos DB ,並找出 Cosmos DB 運算子 角色定義。 然後,選取與該定義相關聯的 「檢視 」選項。

    目前可指派範圍中的角色定義清單的螢幕擷取畫面,已篩選為只包含標題中含有 'Cosmos DB' 的定義。

  8. 在 [Cosmos DB 操作員] 角色定義對話方塊中,觀察指派為此角色定義一部分的動作。

    [Cosmos DB 運算子] 對話方塊的螢幕擷取畫面,其中包含內建角色定義的詳細資料。

  9. 關閉 [Cosmos DB 操作員 ] 角色定義對話方塊。

  10. 返回 [存取控制 (IAM)] 窗格,選取 [新增]。 然後選取 [新增自訂角色]。

    在 [存取控制 (IAM)] 功能表中 [新增] 選項下 [新增自訂角色] 選項的螢幕擷取畫面。

  11. [基本] 窗格中,設定下列選項,然後選取 [ 下一步]:

    價值觀
    自訂角色名稱 Azure Cosmos DB Control Plane Owner
    說明 Can perform all control plane actions for an Azure Cosmos DB account.
    基準許可權 從頭開始

    用於新增自訂角色的「基本」窗格螢幕擷取畫面。

  12. [許可權] 窗格中,選取 [新增許可權]。 然後,在權限對話方塊中搜尋DocumentDB。 最後,選擇 Microsoft.DocumentDB 選項。

    用於新增自訂角色的「權限」窗格的螢幕擷取畫面。

    [新增許可權] 對話方塊的螢幕擷取畫面已篩選至與 'DocumentDB' 相關的許可權,以新增自訂角色。

  13. 在權限對話方塊中,為 選取所有 Microsoft.DocumentDB。 然後,選取 [ 新增 ] 以返回 [*權限] 窗格。

    在自訂角色對話方塊中針對 'DocumentDB' 選取的所有許可權的螢幕擷取畫面。

  14. 返回 [許可權] 窗格,觀察許可權清單。 然後,選取 [ 檢閱 + 建立]。

    「權限」窗格的螢幕擷取畫面,其中多個權限已新增至自訂角色的清單。

  15. 在 [ 檢閱 + 建立 ] 窗格中,檢閱新角色定義的指定選項。 最後,選取 [建立]。

    用於新增自訂角色的「檢閱 + 建立」窗格的螢幕擷取畫面。

  16. 等候入口網站完成建立角色定義。

  17. [存取控制 (IAM)] 窗格中,選取 [ 新增 ],然後選取 [ 新增角色指派]。

    在 [存取控制 (IAM)] 功能表中 [新增] 選項下 [新增角色指派] 選項的螢幕擷取畫面。

  18. [角色] 窗格中,搜尋 Azure Cosmos DB 並選取本指南稍早建立的 Azure Cosmos DB 控制平面擁有者 角色。 然後選取下一步

    用於新增角色指派的「角色」窗格螢幕擷取畫面。

    小提示

    您可以選擇性地篩選角色清單,以僅包含自訂角色。

  19. [ 成員 ] 窗格中,選取 [ 選取成員 ] 選項。 在 [成員] 對話方塊中,選取您想要授與 Azure Cosmos DB 帳戶此存取層級的身分識別,然後使用 [ 選取 ] 選項來確認您的選擇。

    用於新增角色指派的「成員」窗格螢幕擷取畫面。

    新增角色指派的身分識別選取對話方塊的螢幕擷取畫面。

    備註

    此螢幕擷取畫面說明名為 「Kai Carter」 的範例使用者,其主體為 kai@adventure-works.com

  20. 返回 [成員] 窗格,檢閱選取的成員,然後選取 [ 檢閱 + 指派]。

    '成員'窗格的螢幕截圖,其中已選擇身份以進行角色指派。

  21. 在 [ 檢閱 + 指派 ] 窗格中,檢閱新角色指派的指定選項。 最後,選取 [ 檢閱 + 指派]。

    角色指派的 [檢閱 + 建立] 窗格螢幕擷取畫面。

  22. 等候入口網站完成建立角色指派。

  1. Get-AzRoleDefinition 來列出與您的 Azure Cosmos DB 帳戶相關聯的所有角色定義。

    $parameters = @{
        Name = "Cosmos DB Operator"
    }
    Get-AzRoleDefinition @parameters
    
  2. 檢閱輸出,並找出名為 Cosmos DB 內建資料參與者的角色定義。 輸出包含屬性中 Id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    Name             : Cosmos DB Operator
    Id               : 230815da-be43-4aae-9cb4-875f7bd000aa
    IsCustom         : False
    Description      : Lets you manage Azure Cosmos DB accounts, but not access data in them. Prevents access to account keys and connection strings.
    Actions          : {Microsoft.DocumentDb/databaseAccounts/*, Microsoft.Insights/alertRules/*, Microsoft.Authorization/*/read, Microsoft.ResourceHealth/availabilityStatuses/read…}
    NotActions       : {Microsoft.DocumentDB/databaseAccounts/dataTransferJobs/*, Microsoft.DocumentDB/databaseAccounts/readonlyKeys/*, Microsoft.DocumentDB/databaseAccounts/regenerateKey/*, Microsoft.DocumentDB/databaseAccounts/listKeys/*…}
    DataActions      : {}
    NotDataActions   : {}
    AssignableScopes : {/}
    

    備註

    在此範例中, Id 值會是 230815da-be43-4aae-9cb4-875f7bd000aa。 識別碼在 Azure 中的所有角色定義中都是全域唯一的。

  3. Get-AzResourceGroup 來取得目前資源群組的中繼資料。

    $parameters = @{
        Name = "<name-of-existing-resource-group>"
    }
    Get-AzResourceGroup @parameters
    
  4. 觀察上一個命令的輸出。 記錄此資源群組的屬性值 ResourceId,因為此值需要在下一個步驟中使用。

    ResourceGroupName : msdocs-identity-example
    Location          : westus
    ProvisioningState : Succeeded
    ResourceId        : /subscriptions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1/resourcegroups/msdocs-identity-example
    

    備註

    在此範例中, ResourceId 值會是 /subscriptions/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1/resourcegroups/msdocs-identity-example。 此範例使用虛構資料,您的識別碼將與此範例不同。 此字串是一般輸出的截斷範例。

  5. 首先,匯入 Az.Resources 模組。 然後,建立新 Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleDefinition 物件。 在物件中,建立此資源定義,並指定此處列出的值。 針對 AssignableScopes 清單,新增 ResourceId 上一個步驟中記錄的資源群組屬性。 最後,使用角色定義物件作為-Role的參數New-AzRoleDefinition的輸入。

    Import-Module Az.Resources
    
    $parameters = @{
        TypeName = "Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleDefinition"
        Property = @{
            Name = "Azure Cosmos DB Control Plane Owner"
            Description = "Can perform all control plane actions for an Azure Cosmos DB account."
            IsCustom = $true
            Actions = @(
                "Microsoft.DocumentDb/*"
            )
            AssignableScopes = @(
                "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example"
            )
        }
    }
    $role = New-Object @parameters
    
    New-AzRoleDefinition -Role $role
    

    備註

    此範例使用上一個步驟中記錄的 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example 值。 您的實際資源識別碼可能會有所不同。

  6. 檢閱定義建立指令的輸出。 輸出包含屬性中 Name 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    Name             : Azure Cosmos DB Control Plane Owner
    Id               : e4e4e4e4-ffff-aaaa-bbbb-c5c5c5c5c5c5
    IsCustom         : True
    Description      : Can perform all control plane actions for an Azure Cosmos DB account.
    Actions          : {Microsoft.DocumentDb/*}
    AssignableScopes : {/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example}
    

    備註

    在此範例中, Name 值會是 Azure Cosmos DB Control Plane Owner。 為了清楚起見,此範例是部署典型輸出的子集。

  7. 使用New-AzRoleAssignment指派新角色。 使用角色的名稱作為 RoleDefinitionName 參數,並使用您身分的唯一識別碼作為 ObjectId 參數。

    $parameters = @{
        ResourceGroupName = "<name-of-existing-resource-group>"
        ObjectId = "<your-principal-identifier>"
        RoleDefinitionName = "Azure Cosmos DB Control Plane Owner"
    }
    New-AzRoleAssignment @parameters
    
  8. 觀察命令的輸出。 輸出包括 RoleAssignmentId 屬性中指派的唯一識別碼。

    RoleAssignmentName : ffffffff-5555-6666-7777-aaaaaaaaaaaa
    RoleAssignmentId   : /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleAssignments/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1
    Scope              : /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example
    DisplayName        : Kai Carter
    SignInName         : <kai@adventure-works.com>
    RoleDefinitionName : Azure Cosmos DB Control Plane Owner
    RoleDefinitionId   : e4e4e4e4-ffff-aaaa-bbbb-c5c5c5c5c5c5
    

    備註

    在此範例中, RoleAssignmentId 屬性是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.Authorization/roleAssignments/a0a0a0a0-bbbb-cccc-dddd-e1e1e1e1e1e1,這是另一個虛構的範例。 為了清楚起見,此範例是部署典型輸出的子集。

  9. 重複這些步驟,以從您要使用的任何其他身分識別授予存取帳戶之權利。

    小提示

    您可以對任意數量的身分重複這些步驟。 一般而言,這些步驟至少會重複,以允許開發人員使用其人類身分識別存取帳戶,並允許應用程式使用受控識別存取資料。

這很重要

指派角色定義需要您已經擁有要授與角色型存取控制許可的任何身分的唯一識別碼。

在程式碼中驗證控制平面角色型存取

驗證您是否使用應用程式程式碼和 Azure 管理 SDK 正確授與存取權。

using Azure.Identity;
using Azure.ResourceManager;

DefaultAzureCredential credential = new();

ArmClient client = new(credential);
const { CosmosDBManagementClient } = require('@azure/arm-cosmosdb');
const { DefaultAzureCredential } = require('@azure/identity');

const subscriptionId = "<subscription-id>";

const credential = new DefaultAzureCredential();

const client = new CosmosDBManagementClient(credential, subscriptionId);
import { CosmosDBManagementClient } from '@azure/arm-cosmosdb';
import { TokenCredential, DefaultAzureCredential } from '@azure/identity';

let subscriptionId: string = "<subscription-id>";

let credential: TokenCredential = new DefaultAzureCredential();

const client: CosmosDBManagementClient = new CosmosDBManagementClient(credential, subscriptionId);
from azure.mgmt.cosmosdb import CosmosDBManagementClient
from azure.identity import DefaultAzureCredential

subscription_id = "<subscription-id>"

credential = DefaultAzureCredential()

client = CosmosDBManagementClient(credential=credential, subscription=subscription_id)
package main

import (
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmos/armcosmos"
)

const subscriptionId = "<subscription-id>"

func main() {
    credential, _ := azidentity.NewDefaultAzureCredential(nil)
    
    client, _ := armcosmos.NewDatabaseClient(subscriptionId, credential, nil)
}
package com.example;

import com.azure.core.management.profile.AzureProfile;
import com.azure.core.management.AzureEnvironment;
import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.cosmos.CosmosManager;

public class CosmosDB {
    public static void main(String[] args) {
        AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
        DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
          .build();

        CosmosManager manager = CosmosManager.authenticate(credential, profile);
    }
}

授與資料平面角色型存取權

資料平面存取是指在 Azure 服務內讀取和寫入資料的能力,而無法管理帳戶中的資源。 例如,Azure Cosmos DB 資料平面存取可能包含下列功能:

  • 讀取一些帳戶和資源中繼資料
  • 建立、讀取、更新、修補和刪除項目
  • 執行 NoSQL 查詢
  • 從容器的變更摘要中讀取
  • 執行預存程序
  • 管理衝突摘要中的衝突

首先,您必須準備一份包含dataActions清單的角色定義,以授予在 NoSQL Azure Cosmos DB 中讀取、查詢和管理資料的存取權。 在本指南中,您將準備自訂角色。 然後,將新定義的角色指派給身分識別,讓您的應用程式可以存取適用於 NoSQL 的 Azure Cosmos DB 中的資料。

這很重要

取得現有的資料平面角色定義需要下列控制平面權限:

  • Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/read

建立新的資料平面角色定義需要下列控制平面權限:

  • Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/read
  • Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/write

建立新的資料平面角色指派需要下列控制平面權限:

  • Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions/read
  • Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments/read
  • Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments/write

警告

適用於 NoSQL 的 Azure Cosmos DB 原生角色型存取控制不支援屬性 notDataActions 。 任何未指定為允許 dataAction 的動作都會自動排除。

  1. 使用 az cosmosdb sql role definition list列出與適用於 NoSQL 的 Azure Cosmos DB 帳戶相關聯的所有角色定義。

    az cosmosdb sql role definition list \
        --resource-group "<name-of-existing-resource-group>" \
        --account-name "<name-of-existing-nosql-account>"
    
  2. 建立名為 role-definition.json的新 JSON 檔案,用於建立自訂角色。 在此檔案中,建立資源定義,指定下列資料動作:

    Description
    Microsoft.DocumentDB/databaseAccounts/readMetadata 可以讀取帳戶層級的中繼資料
    Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/* 可以執行任何容器層級的資料作業
    Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/* 可以對具有容器的項目執行任何操作
    {
      "RoleName": "Azure Cosmos DB for NoSQL Data Plane Owner",
      "Type": "CustomRole",
      "AssignableScopes": [
        "/"
      ],
      "Permissions": [
        {
          "DataActions": [
            "Microsoft.DocumentDB/databaseAccounts/readMetadata",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*"
          ]
        }
      ]
    }
    
  3. 接下來,使用 az cosmosdb sql role definition create 來建立角色定義。 將 role-definition.json 作為 --body 引數的輸入。

    az cosmosdb sql role definition create \
        --resource-group "<name-of-existing-resource-group>" \
        --account-name "<name-of-existing-nosql-account>" \
        --body "@role-definition.json"
    
  4. 檢閱上一個命令的輸出。 找出您剛才建立的名為 Azure Cosmos DB for NOSQL 資料平面擁有者的角色定義。 輸出包含屬性中 id 角色定義的唯一識別碼。 在本指南中稍後的指派步驟需要用到此值,請將其記錄為 --role-definition-id

    {
      "assignableScopes": [
        "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql"
      ],
      "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql/sqlRoleDefinitions/bbbbbbbb-1111-2222-3333-cccccccccccc",
      "name": "bbbbbbbb-1111-2222-3333-cccccccccccc",
      "permissions": [
        {
          "dataActions": [
            "Microsoft.DocumentDB/databaseAccounts/readMetadata",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*"
          ],
          "notDataActions": []
        }
      ],
      "resourceGroup": "msdocs-identity-example",
      "roleName": "Azure Cosmos DB for NoSQL Data Plane Owner",
      "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions",
      "typePropertiesType": "CustomRole"
    }
    

    備註

    在此範例中, --role-definition-id 值會是 bbbbbbbb-1111-2222-3333-cccccccccccc。 此範例使用虛構資料,您的識別碼將與此範例不同。

  5. 使用在上一步中獲得的id,並通過刪除帳戶名稱後面的所有內容來判斷--scope

    備註

    在此範例中, --scope 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql。 此範例使用虛構資料,您的識別碼將與此範例不同。

  6. 使用az cosmosdb sql role assignment create指派新角色。
    將先前記錄的角色定義識別碼 --role-definition-id 用於引數,
    使用您身分 --principal-id 的唯一識別碼作為引數
    ,最後,使用您帳戶的識別碼作為 --scope 引數。

    az cosmosdb sql role assignment create \
        --resource-group "<name-of-existing-resource-group>" \
        --account-name "<name-of-existing-nosql-account>" \
        --role-definition-id "<id-of-new-role-definition>" \ 
        --principal-id "<id-of-existing-identity>" \
        --scope "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql"
    

    小提示

    如果您嘗試將資料平面角色型存取控制授與您自己的身分識別,您可以使用此命令來取得身分識別:

    az ad signed-in-user show
    

    如需詳細資訊,請參閱az ad signed-in-user

    小提示

    在 Azure Cosmos DB 的角色型存取控制原生實作中, 範圍 是指您想要套用權限之帳戶內資源的細微性。 在最高層級,您可以使用最大範圍,將資料平面角色型存取控制指派的範圍限定為整個帳戶。 此範圍包括帳戶內的所有資料庫和容器:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/
    

    或者,您可以將資料平面角色指派的範圍限定為特定資料庫:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/dbs/<database-name>
    

    最後,您可以將指派範圍限定為單一容器,這是最精細的範圍:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/dbs/<database-name>/colls/<container-name>
    

    在許多情況下,您可以使用相對範圍,而不是完整限定範圍。 例如,您可以使用此相對範圍,從 Azure CLI 命令將資料平面角色型存取控制權限授與特定資料庫和容器:

    /dbs/<database-name>/colls/<container-name>
    

    您也可以使用相對範圍授與所有資料庫和容器的通用存取權:

    /
    
  7. az cosmosdb sql role assignment list 來列出適用於 NoSQL 的 Azure Cosmos DB 帳戶的所有角色指派。 檢查結果,確定您的角色指派已建立。

    az cosmosdb sql role assignment list \
        --resource-group "<name-of-existing-resource-group>" \
        --account-name "<name-of-existing-nosql-account>"
    
  1. 使用 az cosmosdb sql role definition list列出與適用於 NoSQL 的 Azure Cosmos DB 帳戶相關聯的所有角色定義。

    az cosmosdb sql role definition list \
        --resource-group "<name-of-existing-resource-group>" \
        --account-name "<name-of-existing-nosql-account>"
    
  2. 檢閱輸出,並找出名為 Cosmos DB 內建資料參與者的角色定義。 輸出包含屬性中 id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    [
      ...,
      {
        "assignableScopes": [
          "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql"
        ],
        "id": "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002",
        "name": "00000000-0000-0000-0000-000000000002",
        "permissions": [
          {
            "dataActions": [
              "Microsoft.DocumentDB/databaseAccounts/readMetadata",
              "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*",
              "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*"
            ],
            "notDataActions": []
          }
        ],
        "resourceGroup": "msdocs-identity-example",
        "roleName": "Cosmos DB Built-in Data Contributor",
        "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions",
        "typePropertiesType": "BuiltInRole"
      }
      ...
    ]
    

    備註

    在此範例中, id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002。 此範例使用虛構資料,您的識別碼將與此範例不同。

  3. 建立新的 Bicep 檔案來定義您的角色定義。 將檔案命名為 data-plane-role-definition.bicep。 將這些項目新增至 dataActions 定義:

    Description
    Microsoft.DocumentDB/databaseAccounts/readMetadata 可以讀取帳戶層級的中繼資料
    Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/* 可以執行任何容器層級的資料作業
    Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/* 可以對具有容器的項目執行任何操作
    metadata description = 'Create RBAC definition for data plane access to Azure Cosmos DB for NoSQL.'
    
    @description('Name of the Azure Cosmos DB for NoSQL account.')
    param accountName string
    
    @description('Name of the role definition.')
    param roleDefinitionName string = 'Azure Cosmos DB for NoSQL Data Plane Owner'
    
    resource account 'Microsoft.DocumentDB/databaseAccounts@2024-05-15' existing = {
      name: accountName
    }
    
    resource definition 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2024-05-15' = {
      name: guid(account.id, roleDefinitionName)
      parent: account
      properties: {
        roleName: roleDefinitionName
        type: 'CustomRole'
        assignableScopes: [
          account.id
        ]
        permissions: [
          {
            dataActions: [
              'Microsoft.DocumentDB/databaseAccounts/readMetadata'
              'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*'
              'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*'
            ]
          }
        ]
      }
    }
    
    output definitionId string = definition.id
    

    小提示

    在 Azure Cosmos DB 的角色型存取控制原生實作中, 範圍 是指您想要套用權限之帳戶內資源的細微性。 在最高層級,您可以使用最大範圍,將資料平面角色型存取控制指派的範圍限定為整個帳戶。 此範圍包括帳戶內的所有資料庫和容器:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/
    

    或者,您可以將資料平面角色指派的範圍限定為特定資料庫:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/dbs/<database-name>
    

    最後,您可以將指派範圍限定為單一容器,這是最精細的範圍:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/dbs/<database-name>/colls/<container-name>
    

    在許多情況下,您可以使用相對範圍,而不是完整限定範圍。 例如,您可以使用此相對範圍,從 Azure CLI 命令將資料平面角色型存取控制權限授與特定資料庫和容器:

    /dbs/<database-name>/colls/<container-name>
    

    您也可以使用相對範圍授與所有資料庫和容器的通用存取權:

    /
    
  4. 建立名為 data-plane-role-definition 的新 Bicep 參數檔案。bicepparam 在此參數檔案中,將現有適用於 NoSQL 的 Azure Cosmos DB 帳戶名稱指派給參數 accountName

    using './data-plane-role-definition.bicep'
    
    param accountName = '<name-of-existing-nosql-account>'
    
  5. 使用 az deployment group create部署 Bicep 範本。

    az deployment group create \
        --resource-group "<name-of-existing-resource-group>" \
        --parameters data-plane-role-definition.bicepparam \
        --template-file data-plane-role-definition.bicep
    
  6. 建立新的 Bicep 檔案以定義您的角色指派。 將檔案命名為 data-plane-role-assignment.bicep

    metadata description = 'Assign RBAC role for data plane access to Azure Cosmos DB for NoSQL.'
    
    @description('Name of the Azure Cosmos DB for NoSQL account.')
    param accountName string
    
    @description('Id of the role definition to assign to the targeted principal in the context of the account.')
    param roleDefinitionId string
    
    @description('Id of the identity/principal to assign this role in the context of the account.')
    param identityId string = deployer().objectId
    
    resource account 'Microsoft.DocumentDB/databaseAccounts@2024-05-15' existing = {
      name: accountName
    }
    
    resource assignment 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2024-05-15' = {
      name: guid(roleDefinitionId, identityId, account.id)
      parent: account
      properties: {
        principalId: identityId
        roleDefinitionId: roleDefinitionId
        scope: account.id
      }
    }
    
    output assignmentId string = assignment.id
    
  7. 建立名為 data-plane-role-assignment 的新 Bicep 參數檔案。bicepparam 在此參數檔案中,將現有的 Azure Cosmos DB for NoSQL 帳戶名稱指派給 accountName 參數,將先前記錄的角色定義識別碼指派給 roleDefinitionId 參數,並將身分識別的唯一識別碼指派給 identityId 參數。

    using './data-plane-role-assignment.bicep'
    
    param accountName = '<name-of-existing-nosql-account>'
    param roleDefinitionId = '<id-of-new-role-definition>'
    param identityId = '<id-of-existing-identity>'
    

    小提示

    如果您嘗試將資料平面角色型存取控制授與您自己的身分識別,您可以省略 identityId 參數。 然後,Bicep 範本會用 deployer().objectId 來取得部署範本之主體身分識別。 如需詳細資訊,請參閱deployer

  8. 使用 az deployment group create部署 Bicep 範本。

    az deployment group create \
        --resource-group "<name-of-existing-resource-group>" \
        --parameters data-plane-role-assignment.bicepparam \
        --template-file data-plane-role-assignment.bicep
    
  9. 重複這些步驟,以從您要使用的任何其他身分識別授予存取帳戶之權利。

    小提示

    您可以對任意數量的身分重複這些步驟。 通常,這些步驟至少會重複,以允許開發人員使用其人類身分存取帳戶。 您也可以重複這些步驟,以允許應用程式使用受控識別存取資源。

  1. Get-AzCosmosDBSqlRoleDefinition 來列出與適用於 NoSQL 的 Azure Cosmos DB 帳戶相關聯的所有角色定義。

    $parameters = @{
        ResourceGroupName = "<name-of-existing-resource-group>"
        AccountName = "<name-of-existing-nosql-account>"
    }
    Get-AzCosmosDBSqlRoleDefinition @parameters
    
  2. 檢閱輸出,並找出名為 Cosmos DB 內建資料參與者的角色定義。 輸出包含屬性中 Id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    Id                         : /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002
    RoleName                   : Cosmos DB Built-in Data Contributor
    Type                       : BuiltInRole
    AssignableScopes           : {/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccountsmsdocs-identity-example-nosql}
    Permissions.DataActions    : {Microsoft.DocumentDB/databaseAccounts/readMetadata, Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*, Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*}
    Permissions.NotDataActions : 
    

    備註

    在此範例中, Id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002。 此範例使用虛構資料,您的識別碼將與此範例不同。 不過,識別碼 (00000000-0000-0000-0000-000000000002) 在您帳戶中的所有角色定義中都是唯一的。

  3. 建立新的角色定義使用New-AzCosmosDBSqlRoleDefinition。 針對 DataAction 參數,指定此處列出的資料動作:

    Description
    Microsoft.DocumentDB/databaseAccounts/readMetadata 可以讀取帳戶層級的中繼資料
    Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/* 可以執行任何容器層級的資料作業
    Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/* 可以對具有容器的項目執行任何操作
    $parameters = @{
        ResourceGroupName = "<name-of-existing-resource-group>"
        AccountName = "<name-of-existing-nosql-account>"
        RoleName = "Azure Cosmos DB for NoSQL Data Plane Owner"
        Type = "CustomRole"
        AssignableScope = @(
            "/"
        )
        DataAction = @(
            "Microsoft.DocumentDB/databaseAccounts/readMetadata",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*",
            "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*"
        )
    }
    New-AzCosmosDBSqlRoleDefinition @parameters
    

    小提示

    在 Azure Cosmos DB 的角色型存取控制原生實作中, 範圍 是指您想要套用權限之帳戶內資源的細微性。 在最高層級,您可以使用最大範圍,將資料平面角色型存取控制指派的範圍限定為整個帳戶。 此範圍包括帳戶內的所有資料庫和容器:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/
    

    或者,您可以將資料平面角色指派的範圍限定為特定資料庫:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/dbs/<database-name>
    

    最後,您可以將指派範圍限定為單一容器,這是最精細的範圍:

    /subscriptions/<subscription-id>/resourcegroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<account-name>/dbs/<database-name>/colls/<container-name>
    

    在許多情況下,您可以使用相對範圍,而不是完整限定範圍。 例如,您可以使用此相對範圍,從 Azure CLI 命令將資料平面角色型存取控制權限授與特定資料庫和容器:

    /dbs/<database-name>/colls/<container-name>
    

    您也可以使用相對範圍授與所有資料庫和容器的通用存取權:

    /
    
  4. Get-AzCosmosDBSqlRoleDefinition 來列出與適用於 NoSQL 的 Azure Cosmos DB 帳戶相關聯的所有角色定義。

    $parameters = @{
        ResourceGroupName = "<name-of-existing-resource-group>"
        AccountName = "<name-of-existing-nosql-account>"
    }
    Get-AzCosmosDBSqlRoleDefinition @parameters    
    
  5. 檢閱上一個命令的輸出。 找出您剛才建立的名為 Azure Cosmos DB for NOSQL 資料平面擁有者的角色定義。 輸出包含屬性中 Id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

    Id                         : /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql/sqlRoleDefinitions/bbbbbbbb-1111-2222-3333-cccccccccccc
    RoleName                   : Azure Cosmos DB for NoSQL Data Plane Owner
    Type                       : CustomRole
    AssignableScopes           : {/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql}
    Permissions.DataActions    : {Microsoft.DocumentDB/databaseAccounts/readMetadata, Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*, Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*}
    Permissions.NotDataActions :
    

    備註

    在此範例中, Id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourcegroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql/sqlRoleDefinitions/bbbbbbbb-1111-2222-3333-cccccccccccc。 此範例使用虛構資料,您的識別碼將與此範例不同。

  6. 使用 Get-AzCosmosDBAccount 來獲取您當前帳戶的中繼資料。

    $parameters = @{
        ResourceGroupName = "<name-of-existing-resource-group>"
        Name = "<name-of-existing-nosql-account>"
    }    
    Get-AzCosmosDBAccount @parameters | Select -Property Id
    
  7. 觀察上一個命令的輸出。 請記錄此帳戶的Id屬性值,因為在下一步中需要使用該值。

    Id
    --    
    /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql
    

    備註

    在此範例中, Id 值會是 /subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql。 此範例使用虛構資料,您的識別碼將與此範例不同。

  8. 使用 New-AzCosmosDBSqlRoleAssignment 指派新角色。 使用先前記錄的角色定義識別碼 RoleDefinitionId 來設定參數,並將身分的唯一識別碼使用到參數上 PrincipalId 。 最後,使用您帳戶的識別碼作為 Scope 參數。

    $parameters = @{
        ResourceGroupName = "<name-of-existing-resource-group>"
        AccountName = "<name-of-existing-nosql-account>"
        RoleDefinitionId = "<id-of-new-role-definition>"
        PrincipalId = "<id-of-existing-identity>"
        Scope = "/subscriptions/aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e/resourceGroups/msdocs-identity-example/providers/Microsoft.DocumentDB/databaseAccounts/msdocs-identity-example-nosql"
    }    
    New-AzCosmosDBSqlRoleAssignment @parameters
    

    小提示

    如果您嘗試將資料平面角色型存取控制授與您自己的身分識別,您可以使用此命令來取得身分識別:

    Get-AzADUser -SignedIn | Format-List `
        -Property Id, DisplayName, Mail, UserPrincipalName
    

    如需詳細資訊,請參閱Get-AzADUser

  9. 使用 Get-AzCosmosDBSqlRoleAssignment 列出適用於 NoSQL 的 Azure Cosmos DB 帳戶的所有角色指派。 檢查結果,確定您的角色指派已建立。

    $parameters = @{
        ResourceGroupName = "<name-of-existing-resource-group>"
        AccountName = "<name-of-existing-nosql-account>"
    }
    Get-AzCosmosDBSqlRoleAssignment @parameters
    

警告

Azure 入口網站不支援管理資料平面的角色型存取控制。

在程式碼中驗證資料平面角色型存取

請驗證您是否透過應用程式程式碼及 Azure SDK 正確授予存取權。

using Azure.Core;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

string endpoint = "<account-endpoint>";

TokenCredential credential = new DefaultAzureCredential();

CosmosClient client = new(endpoint, credential);

Container container = client.GetContainer("<database-name>", "<container-name>");

await container.ReadItemAsync<dynamic>("<item-id>", new PartitionKey("<partition-key>"));
const { CosmosClient } = require('@azure/cosmos');
const { DefaultAzureCredential } = require('@azure/identity');

const endpoint = '<account-endpoint>';

const credential = new DefaultAzureCredential();

const client = new CosmosClient({ endpoint, aadCredentials:credential});

const container = client.database('<database-name>').container('<container-name>');

await container.item('<item-id>', '<partition-key>').read<String>();
import { Container, CosmosClient, CosmosClientOptions } from '@azure/cosmos'
import { TokenCredential, DefaultAzureCredential } from '@azure/identity'

let endpoint: string = '<account-endpoint>';

let credential: TokenCredential = new DefaultAzureCredential();

let options: CosmosClientOptions = {
  endpoint: endpoint,
  aadCredentials: credential
};

const client: CosmosClient = new CosmosClient(options);

const container: Container = client.database('<database-name>').container('<container-name>');

await container.item('<item-id>', '<partition-key>').read<String>();
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential

endpoint = "<account-endpoint>"

credential = DefaultAzureCredential()

client = CosmosClient(endpoint, credential=credential)

container = client.get_database_client("<database-name>").get_container_client("<container-name>")

container.read_item(
    item="<item-id>",
    partition_key="<partition-key>",
)
import (
    "context"
    
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

const endpoint = "<account-endpoint>"

func main() {
    credential, _ := azidentity.NewDefaultAzureCredential(nil)
    client, _ := azcosmos.NewClient(endpoint, credential, nil)
    
    database, _ := client.NewDatabase("<database-name>")
    container, _ := database.NewContainer("<container-name>")
    
    _, err := container.ReadItem(context.TODO(), azcosmos.NewPartitionKeyString("<partition-key>"), "<item-id>", nil)
    if err != nil {
        panic(err)
    }
}
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.models.PartitionKey;
import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;

public class NoSQL {
    public static void main(String[] args) {   
        DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
            .build();
            
        CosmosClient client = new CosmosClientBuilder()
            .endpoint("<account-endpoint>")
            .credential(credential)
            .buildClient();

        CosmosContainer container = client.getDatabase("<database-name>").getContainer("<container-name>");

        container.readItem("<item-id>", new PartitionKey("<partition-key>"), Object.class);
    }
}
use azure_data_cosmos::CosmosClient;
use azure_identity::DefaultAzureCredential;

fn main() {
    let credential = DefaultAzureCredential::new().unwrap();
    let client = CosmosClient::new("<account-endpoint>", credential, None).unwrap();

    let container = client.database_client("<database-name>").container_client("<container-name>");

    let response = container.read_item("<partition-key>", "<item-id>", None);
    tokio::runtime::Runtime::new().unwrap().block_on(response).unwrap();
}