共用方式為


使用角色型存取控制和 Microsoft Entra ID 連線到 Azure DocumentDB

Azure DocumentDB 支援 Microsoft Entra ID,並支援原生 DocumentDB 認證。 每個叢集皆啟用原生認證並內建一個管理使用者。

基於角色的存取控制提供集中機制,透過 Microsoft Entra ID 分配並執行權限,確保只有授權身份能對叢集執行操作。 這種方法簡化了治理,支援最低權限原則,並使稽核變得簡單,幫助組織隨著部署的成長保持營運完整性和合規性。 在 Azure DocumentDB 中管理存取權涉及兩個不同層級:

  • Azure 角色導向存取,用於管理叢集作為 Azure 資源(例如讀取元資料、管理防火牆規則及設定私有端點)
  • DocumentDB 存取權限,用於在叢集上的資料庫與集合中讀寫資料。

啟用 Microsoft Entra ID 以允許 Microsoft Entra 主體(使用者、服務主體或受管理身份)驗證叢集。 Microsoft Entra ID 認證是透過 OpenID Connect(OIDC)實作。 用戶端向 MongoDB 驅動程式提供 Entra 發行的 OIDC 存取權杖。 叢集必須啟用原生認證;支援的配置為僅限原生或原生且支援 Microsoft Entra ID 認證。 Microsoft Entra ID 不能是唯一的認證方式。

備註

配置完成後,你可以隨時啟用或更改叢集的認證方法。 更改認證方法 不需要 叢集重啟,且不會造成干擾。 當建立叢集時,必須啟用原生的 DocumentDB 認證。 你可以在叢集完成配置後關閉原生認證。

使用Microsoft Entra ID 進行驗證的優點包括:

  • Azure 服務間的統一身份與登入。
  • 集中管理憑證、密碼政策與輪替。
  • 支援 Microsoft Entra ID 的無密碼及多重驗證方法。
  • 應用程式採用憑證式認證,消除儲存密碼。

啟用 Microsoft Entra ID 驗證後,你可以在叢集上註冊一個或多個 Microsoft Entra 主體,作為管理員或非管理員使用者。 註冊的主體會成為 Azure 資源 Microsoft.DocumentDB/mongoClusters/users ,並被複製到資料庫中;將這些主體映射到 MongoDB 資料庫角色後,即可獲得相應的資料庫權限。 此認證形式支援多種主體類型,包括:人類使用者、服務主體(應用程式)、使用者指派及系統指派的管理身份。

備註

你可以同時設定多個 Microsoft Entra ID 身份及不同身份類型作為叢集的管理員。 Microsoft Entra ID 身份類型包括但不限於:

  • 人類身份
  • 使用者指派的受控識別
  • 系統指派的受控識別
  • 工作負載身分識別

所有身份類型都可以同時擔任管理員。

管理員擁有管理叢集及其資料的完整權限。 非管理使用者可以新增用於不需要管理員權限的持續生產任務。 非管理使用者通常擁有受限角色,例如對特定資料庫的唯讀或可讀寫存取權限,但無法執行整個叢集的管理操作。

在使用此功能前,請先檢視以下考量事項:

  • 主要叢集和複本叢集上的驗證方法會 獨立管理
  • Microsoft Entra 的主體會持續存在於叢集元資料中。 如果刪除 Microsoft Entra ID 中的主體,對應的叢集使用者仍會保留,但將無法再取得新的權杖。 現有代幣有效期至到期(通常從 代幣發行日起最多90分鐘內)。
  • 若要立即撤銷存取權,請將主體從叢集中移除(刪除 users/<principal-id> 資源),並移除所有相關的資料庫角色;資料庫管理員必須處理所有權轉移或已刪除主體的清理。

先決條件

  • Azure 訂用帳戶

    • 如果您沒有 Azure 訂用帳戶,請建立 免費帳戶
  • 一個現有的 Azure DocumentDB 叢集

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

管理 Azure 角色型存取控制

Azure 角色基礎存取控制是指在不管理資料的情況下,管理 Azure 服務的資源。 例如,Azure DocumentDB 叢集的角色基礎存取可能包含以下功能:

  • 讀取所有帳戶和資源中繼資料
  • 讀取並重新產生連接字串
  • 管理資料庫與收藏
  • 修改帳戶屬性

Azure DocumentDB 支援 Azure 角色為基礎的存取控制用於 mongoCluster 資源類型。 以下資源類型的mongoCluster可於 Azure 角色基礎存取控制中,針對個別指派及自訂角色基礎存取控制角色建立提供:

Description
Microsoft.DocumentDB/mongoClusters/read 讀取 mongoCluster 資源或列出所有 mongoCluster 資源。
Microsoft.DocumentDB/mongoClusters/write 建立或更新指定 mongoCluster 資源的屬性或標籤。
Microsoft.DocumentDB/mongoClusters/delete 刪除指定的 mongoCluster 資源。
Microsoft.DocumentDB/mongoClusters/PrivateEndpointConnectionsApproval/action 管理 mongoCluster 資源的私人端點連線
Microsoft.DocumentDB/mongoClusters/listConnectionStrings/action 列出指定 mongoCluster 資源的連接字串
Microsoft.DocumentDB/mongoClusters/firewallRules/read 讀取防火牆規則或列出指定 mongoCluster 資源的所有防火牆規則。
Microsoft.DocumentDB/mongoClusters/firewallRules/write 在指定的 mongoCluster 資源上建立或更新防火牆規則。
Microsoft.DocumentDB/mongoClusters/firewallRules/delete 刪除指定 mongoCluster 資源的現有防火牆規則。
Microsoft.DocumentDB/mongoClusters/privateEndpointConnectionProxies/read 讀取指定 mongoCluster 資源的私人端點連線代理。
Microsoft.DocumentDB/mongoClusters/privateEndpointConnectionProxies/write 在指定的 mongoCluster 資源上建立或更新私人端點連線 Proxy。
Microsoft.DocumentDB/mongoClusters/privateEndpointConnectionProxies/delete 刪除指定 mongoCluster 資源的現有私用端點連接代理。
Microsoft.DocumentDB/mongoClusters/privateEndpointConnectionProxies/validate/action 驗證指定 mongoCluster 資源的私人端點連線代理。
Microsoft.DocumentDB/mongoClusters/privateEndpointConnections/read 讀取私人端點連線,或列出指定 mongoCluster 資源的所有私人端點連線。
Microsoft.DocumentDB/mongoClusters/privateEndpointConnections/write 在指定的 mongoCluster 資源上建立或更新私人端點連線。
Microsoft.DocumentDB/mongoClusters/privateEndpointConnections/delete 刪除指定 mongoCluster 資源的現有私人端點連線。
Microsoft.DocumentDB/mongoClusters/privateLinkResources/read 讀取私人連結資源,或列出指定 mongoCluster 資源的所有私人連結資源。
Microsoft.DocumentDB/mongoClusters/users/read 讀取使用者或列出指定 mongoCluster 資源的所有使用者。
Microsoft.DocumentDB/mongoClusters/users/write 在指定 mongoCluster 資源上建立或更新使用者。
Microsoft.DocumentDB/mongoClusters/users/delete 刪除指定 mongoCluster 資源的現有使用者。
  1. 開啟新的終端機。

  2. 登入 Azure CLI。

  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 DocumentDB RBAC Owner",
      "IsCustom": true,
      "Description": "Can perform all Azure role-based access control actions for Azure DocumentDB clusters.",
      "Actions": [
        "Microsoft.DocumentDb/mongoClusters/*"
      ],
      "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 Azure role-based access control actions for Azure DocumentDB clusters.",
      "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 DocumentDB RBAC Owner",
      "roleType": "CustomRole"
    }
    

    備註

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

  1. 開啟新的終端機。

  2. 登入 Azure CLI。

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

    Description
    Microsoft.DocumentDb/mongoClusters/* 啟用所有可能的動作。
    metadata description = 'Create RBAC definition for Azure role-based access control access to Azure DocumentDB.'
    
    @description('Name of the role definition.')
    param roleDefinitionName string = 'Azure DocumentDB RBAC Owner'
    
    @description('Description of the role definition.')
    param roleDefinitionDescription string = 'Can perform all Azure role-based access control actions for Azure DocumentDB clusters.'
    
    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/mongoClusters/*'
            ]
          }
        ]
        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 Azure role-based access control access to Azure DocumentDB.'
    
    @description('Id of the role definition to assign to the targeted principal in the context of the cluster.')
    param roleDefinitionId string
    
    @description('Id of the identity/principal to assign this role in the context of the cluster.')
    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
    
  1. 登入 Azure 入口網站 (https://portal.azure.com)。

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

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

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

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

  6. 存取控制(IAM) 面板中,選擇 新增。 然後選取 [新增自訂角色]。

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

    價值觀
    自訂角色名稱 Azure DocumentDB RBAC Owner
    說明 Can perform all Azure role-based access control actions for Azure DocumentDB clusters.
    基準許可權 從頭開始
  8. [許可權] 窗格中,選取 [新增許可權]。 然後,在權限對話方塊中搜尋DocumentDB。 最後,選擇 Microsoft.DocumentDB/mongoClusters 選項。

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

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

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

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

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

  14. 角色 面板中,搜尋 Azure DocumentDB 並選擇本指南中先前建立的 Azure DocumentDB RBAC 擁有者 角色。 然後選取下一步

    小提示

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

  15. [ 成員 ] 窗格中,選取 [ 選取成員 ] 選項。 在成員對話框中,選擇你想授予 Azure DocumentDB 叢集此層級存取權的身份,然後使用 選擇 選項確認你的選擇。

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

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

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

  1. 開啟新的終端機。

  2. 登入 Azure CLI。

  3. 請檢查您的目標 Azure 訂用帳戶。

    az account show
    
  4. 建立一個新的 Terraform 檔案來定義你的角色定義。 為檔案命名為 control-plane-role-definition.tf. 將這些項目新增至 actions 定義:

    Description
    Microsoft.DocumentDb/mongoClusters/* 啟用所有可能的動作。
    variable "role_definition_name" {
      type        = string
      description = "Name of the role definition."
      default     = "Azure DocumentDB RBAC Owner"
    }
    
    variable "role_definition_description" {
      type        = string
      description = "Description of the role definition."
      default     = "Can perform all Azure role-based access control actions for Azure DocumentDB clusters."
    }
    
    terraform {
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
    data "azurerm_client_config" "current" {}
    
    data "azurerm_resource_group" "existing" {
      name = "<name-of-existing-resource-group>"
    }
    
    resource "azurerm_role_definition" "control_plane" {
      name               = var.role_definition_name
      scope              = data.azurerm_resource_group.existing.id
      description        = var.role_definition_description
    
      permissions {
        actions = [
          "Microsoft.DocumentDb/mongoClusters/*"
        ]
      }
    
      assignable_scopes = [
        data.azurerm_resource_group.existing.id
      ]
    }
    
    output "definition_id" {
      value = azurerm_role_definition.control_plane.id
    }
    
  5. 啟動 Terraform 部署。

    terraform init --upgrade
    
  6. 建立角色定義的執行計畫,並儲存到名為 role-definition.tfplan 的檔案。

    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform plan --out "role-definition.tfplan"
    
  7. 套用執行計畫來部署角色定義到 Azure。

    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform apply "role-definition.tfplan"
    
  8. 查看部署結果。 輸出包含屬性中 definition_id 角色定義的唯一識別碼。 記錄此值,因為本指南稍後的指派步驟需要使用該值。

  9. 建立一個新的 Terraform 檔案來定義你的角色分配。 檔案名稱為 control-plane-role-assignment.tf.

    variable "role_definition_id" {
      type        = string
      description = "Id of the role definition to assign to the targeted principal in the context of the cluster."
    }
    
    variable "identity_id" {
      type        = string
      description = "Id of the identity/principal to assign this role in the context of the cluster."
    }
    
    terraform {
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
    data "azurerm_resource_group" "existing" {
      name = "<name-of-existing-resource-group>"
    }
    
    resource "azurerm_role_assignment" "control_plane" {
      scope              = data.azurerm_resource_group.existing.id
      role_definition_id = var.role_definition_id
      principal_id       = var.identity_id
    }
    
  10. 建立一個新的 Terraform 變數檔案,名為 control-plane-role-assignment.tfvars。 在這個變數檔案中;將先前記錄的角色定義識別碼指派給 role_definition_id 變數,並將你身份的唯一識別碼指派給變 identity_id 數。

    role_definition_id = "<id-of-new-role-definition>"
    identity_id        = "<id-of-existing-identity>"
    
  11. 初始化並套用這個 Terraform 設定。

    terraform init --upgrade
    
    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform plan --var-file="control-plane-role-assignment.tfvars" --out "role-assignment.tfplan"
    
    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform apply "role-assignment.tfplan"
    

啟用 Microsoft Entra ID 驗證

當你建立 Azure DocumentDB 叢集時,叢集預設會只使用原生認證。 若要啟用使用 Microsoft Entra ID 進行驗證,請開啟 Microsoft Entra ID 認證方法,並將 Microsoft Entra ID 身份加入叢集。

  1. 請使用az ad signed-in-user取得當前登入帳戶的詳細資訊。

    az ad signed-in-user show
    
  2. 命令會輸出包含各種欄位的 JSON 回應。

    {
      "@odata.context": "<https://graph.microsoft.com/v1.0/$metadata#users/$entity>",
      "businessPhones": [],
      "displayName": "Kai Carter",
      "givenName": "Kai",
      "id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
      "jobTitle": "Senior Sales Representative",
      "mail": "<kai@adventure-works.com>",
      "mobilePhone": null,
      "officeLocation": "Redmond",
      "preferredLanguage": null,
      "surname": "Carter",
      "userPrincipalName": "<kai@adventure-works.com>"
    }
    

    小提示

    記錄id欄位的數值。 在這個例子中,該值為 aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb。 這個值接著可以用在各種腳本中,授予你目前帳戶基於角色的存取控制權限給 Azure 資源。 如果您改用受控識別,則可以透過 az identity show 命令取得該受控識別的 id

  3. 透過更新叢集資源,將以下內容納入MicrosoftEntraIDauthConfig.allowedModes陣列,啟用 Microsoft Entra ID 認證:

    az resource patch \
        --resource-group "<resource-group>" \
        --name "<cluster-name>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters" \
        --properties '{"authConfig":{"allowedModes":["MicrosoftEntraID","NativeAuth"]}}' \
        --latest-include-preview
    

    備註

    請將 <resource-group><cluster-name> 取代為您的值。

  4. 透過使用az resource show在叢集上讀取authConfig屬性,以驗證變更是否被應用。

    az resource show \
        --resource-group "<resource-group>" \
        --name "<cluster-name>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters" \
        --query "properties.authConfig" \
        --latest-include-preview
    

    備註

    輸出應該包含該清單。allowedModes 若成功啟用 Microsoft Entra ID,陣列中包含 NativeAuthMicrosoftEntraID

  1. (可選)取得你打算在叢集上註冊的 Microsoft Entra 主體的唯一識別碼。 你可以用 Azure CLI 以下指令之一取得:

    • 目前登入身份

      az ad signed-in-user show      
      
    • 另一個以友善名稱識別的人類身份

      az ad user show \
        --id "<user-alias-and-domain>"
      
    • 使用應用程式識別碼的服務主體

      az ad sp show \
        --id "<application-id>"
      
    • 使用資源群組和名稱的受管理身份

      az identity show \
        --resource-group "<resource-group>" \
        --name "<managed-identity-name>"      
      
  2. 建立一個小型 Bicep 範本,更新叢集 authConfig 以包含 Microsoft Entra ID(另存為 enable-entra-id.bicep):

    param clusterName string
    param location string = resourceGroup().location
    
    resource cluster 'Microsoft.DocumentDB/mongoClusters@2025-09-01' = {
      name: clusterName
      location: location
      properties: {
        authConfig: {
          allowedModes: [
            'MicrosoftEntraID'
            'NativeAuth'
          ]
        }
      }
    }
    
  3. 部署範本以更新叢集:

    az deployment group create \
        --resource-group "<resource-group>" \
        --template-file enable-entra-id.bicep \
        --parameters clusterName="<cluster-name>"
    
  4. 使用az resource show來驗證叢集上的authConfig屬性。

    az resource show \
        --resource-group "<resource-group>" \
        --name "<cluster-name>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters" \
        --query "properties.authConfig" \
        --latest-include-preview
    

    備註

    輸出應該包含allowedModes清單。 若成功啟用 Microsoft Entra ID,陣列中包含 NativeAuthMicrosoftEntraID

  1. 在 Azure 入口網站的 Home 窗格中,找到並選擇 Microsoft Entra ID 選項。

    Azure 入口網站「首頁」中 Microsoft Entra ID 選項的截圖。

    小提示

    如果沒有這個選項,請選擇「更多服務」,然後用「Entra」搜尋 Microsoft Entra ID

  2. 在 Microsoft Entra ID 租戶的概覽窗格中,選擇服務選單的管理區塊中的使用者

    Microsoft Entra ID 租戶服務選單中「使用者」選項的截圖。

  3. 在使用者列表中,選擇你想要獲得更多細節的身份(使用者)。

    Microsoft Entra ID 租戶的使用者列表截圖,並標示了一個範例使用者。

    備註

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

  4. 在特定使用者的詳細面板中,觀察 物件 ID 屬性的值。

    使用者詳細資料窗格的截圖,標示了「物件 ID」。

    小提示

    記錄 物件 ID 屬性的值。 在這個例子中,該值為 aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb。 這個值接著可以用在各種腳本中,授予你目前帳戶基於角色的存取控制權限給 Azure 資源。 如果你使用管理身份,步驟類似。

  5. 前往現有的 Azure DocumentDB 叢集資源。

  6. 在叢集選單中,在 設定中選擇 認證

  7. 認證方法 區塊中,選擇 Native DocumentDB 與 Microsoft Entra ID ,即可啟用 Microsoft Entra ID 認證與原生認證。

  8. 選擇 儲存 以維持變更。

  9. 認證 方法 區塊現在應該會同時列出 NativeAuthMicrosoftEntraID 為啟用的方法。

  1. (可選)取得你打算在叢集上註冊的 Microsoft Entra 主體的唯一識別碼。 你可以用 Azure CLI 以下指令之一取得:

    • 目前登入身份

      az ad signed-in-user show      
      
    • 另一個以友善名稱識別的人類身份

      az ad user show \
        --id "<user-alias-and-domain>"
      
    • 使用應用程式識別碼的服務主體

      az ad sp show \
        --id "<application-id>"
      
    • 使用資源群組和名稱的受管理身份

      az identity show \
        --resource-group "<resource-group>" \
        --name "<managed-identity-name>"      
      
  2. 建立一個 Terraform 設定檔,讓你現有叢集啟用 Microsoft Entra ID 認證。 將檔案儲存為 enable-entra-id。tf

    variable "cluster_name" {
      type        = string
      description = "Name of the existing cluster"
    }
    
    variable "resource_group_name" {
      type        = string
      description = "Name of the existing resource group"
    }
    
    terraform {
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
    data "azurerm_resource_group" "existing" {
      name = var.resource_group_name
    }
    
    data "azurerm_mongo_cluster" "existing" {
      name                = var.cluster_name
      resource_group_name = data.azurerm_resource_group.existing.name
    }
    
    resource "azurerm_mongo_cluster" "enable_entra" {
      name                   = data.azurerm_mongo_cluster.existing.name
      resource_group_name    = data.azurerm_resource_group.existing.name
      location               = data.azurerm_mongo_cluster.existing.location
      administrator_username = data.azurerm_mongo_cluster.existing.administrator_username
      administrator_password = data.azurerm_mongo_cluster.existing.administrator_password
      shard_count            = data.azurerm_mongo_cluster.existing.shard_count
      compute_tier           = data.azurerm_mongo_cluster.existing.compute_tier
      high_availability_mode = data.azurerm_mongo_cluster.existing.high_availability_mode
      storage_size_in_gb     = data.azurerm_mongo_cluster.existing.storage_size_in_gb
      version                = data.azurerm_mongo_cluster.existing.version
    
      # Enable both Microsoft Entra ID and Native authentication
      authentication_enabled = true
    }
    

    小提示

    欲了解更多使用該 azurerm_mongo_cluster 資源的選項資訊,請參閱 azurerm Terraform 註冊局中的提供者文件

  3. 建立一個名為 enable-entra-id.tfvars 的變數檔案,裡面有你的叢集細節:

    cluster_name        = "<cluster-name>"
    resource_group_name = "<resource-group>"
    
  4. 初始化並套用 Terraform 設定以啟用 Microsoft Entra ID 認證:

    terraform init --upgrade
    
    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform plan --var-file="enable-entra-id.tfvars" --out "enable-entra.tfplan"
    
    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform apply "enable-entra.tfplan"
    
  5. 使用az resource show來驗證叢集上的authConfig屬性。

    az resource show \
        --resource-group "<resource-group>" \
        --name "<cluster-name>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters" \
        --query "properties.authConfig" \
        --latest-include-preview
    

    備註

    輸出應該包含allowedModes清單。 若成功啟用 Microsoft Entra ID,陣列中包含 NativeAuthMicrosoftEntraID

管理 DocumentDB 的 Microsoft Entra ID 身份與原生使用者

當 Azure DocumetnDB 叢集啟用 Microsoft Entra ID 認證時,你可以將一個或多個 Microsoft Entra ID 主體加入該叢集作為 管理員使用者 。 Microsoft Entra ID 系統管理員可以是 Microsoft Entra ID 使用者、服務主體或受管理的身分。 您可以隨時設定多個Microsoft Entra ID 系統管理員。

系統管理的 Entra ID 使用者會在 Microsoft.DocumentDB/mongoClusters/users 下建立為 Azure 實體,並複寫到資料庫中。

此外,一旦啟用 Microsoft Entra ID 驗證,便可隨時將一或多名非管理員的 Microsoft Entra ID 使用者新增至叢集。 非管理使用者通常用於不需要系統管理許可權的持續生產工作。

對於 Azure DocumentDB,這種存取權是透過在叢集上註冊 Microsoft Entra 主體並將它們對應到 MongoDB 資料庫角色來授予的(例如,在某個資料庫上的 readWrite 或在 admin 資料庫上的 root)。 已註冊的主體會建立為類型為 Microsoft.DocumentDB/mongoClusters/users 的 Azure 資源,其名稱採用 <cluster-name>/users/<principal-id> 形式。

管理員擁有管理叢集及其資料的完整權限,包括完整的使用者管理功能。 非管理使用者可透過特定的 MongoDB 資料庫角色獲得叢集的讀寫或唯讀權限。 readWriteAnyDatabaseclusterAdmin 角色一起授與叢集的完整讀寫權限,包括資料庫管理和資料庫作業的權限。 readAnyDatabase 角色可用來授與叢集的唯讀權限。 你不能分別指派 readWriteAnyDatabaseclusterAdmin 角色,它們必須一起授權,才能獲得完全的讀寫權限。

非管理(次要)使用者與安全主體在叢集上被授予有限的使用者管理權限,詳見下表:

安全性提供者 Role 建立使用者 DeleteUser UpdateUser ListUser
Microsoft Entra ID 讀寫存取(readWriteAnyDatabase、clusterAdmin) ✔️
Microsoft Entra ID 唯讀 (readAnyDatabase) ✔️
原生 DocumentDB 讀寫存取(readWriteAnyDatabase、clusterAdmin) 只為變更其密碼 ✔️
原生 DocumentDB 唯讀 (readAnyDatabase) 只為變更其密碼 ✔️
  1. 請使用以下指令之一取得您想授權存取的 Microsoft Entra 主體的唯一識別碼(物件 ID):

    • 目前登入身份

      az ad signed-in-user show      
      
    • 另一個以友善名稱識別的人類身份

      az ad user show \
        --id "<user-alias-and-domain>"
      
    • 使用應用程式識別碼的服務主體

      az ad sp show \
        --id "<application-id>"
      
    • 使用資源群組和名稱的受管理身份

      az identity show \
        --resource-group "<resource-group>" \
        --name "<managed-identity-name>"      
      
  2. 在叢集上註冊主體,並將其對應到 MongoDB 資料庫角色。 以下範例將主體註冊為 readWrite 資料庫中的 sales 使用者:

    az resource create \
        --resource-group "<resource-group>" \
        --name "<cluster-name>/users/<principal-id>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters/users" \
        --location "<cluster-region>" \
        --properties '{"identityProvider":{"type":"MicrosoftEntraID","properties":{"principalType":"User"}},"roles":[{"db":"sales","role":"readWrite"}]}' \
        --latest-include-preview
    
    • principalType替換為對於應用程式/服務主體的servicePrincipal或受管理的身分識別的ManagedIdentity
    • 要授予管理員權限,請在陣列中使用{"db":"admin","role":"root"}roles
  3. 列出所有註冊的主體及其映射角色(叢集層級視圖):

    az rest \
        --method "GET" \
        --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.DocumentDB/mongoClusters/<cluster-name>/users?api-version=2025-09-01"
    
    • 回應包含一個使用者資源陣列,每個資源都有 identityProvider 元資料,以及 roles 一個顯示映射資料庫角色的陣列。
  4. 取得特定註冊主事的詳細資料(替換 <principal-id>):

    az resource show \
        --resource-group "<resource-group>" \
        --name "<cluster-name>/users/<principal-id>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters/users" \
        --latest-include-preview
    
  5. 移除已註冊的主體 (撤銷資料平面存取權):

    az resource delete \
        --resource-group "<resource-group>" \
        --name "<cluster-name>/users/<principal-id>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters/users" \
        --latest-include-preview
    
  1. 建立一個 Bicep 檔案 (例如 register-principal.bicep),用於註冊主體並對應資料庫角色:

    param clusterName string
    param principalId string
    param location string = resourceGroup().location
    param principalType string = 'User'
    param roles array = [
      {
        db: 'sales'
        role: 'readWrite'
      }
    ]
    
    resource user 'Microsoft.DocumentDB/mongoClusters/users@2025-09-01' = {
      name: '${clusterName}/users/${principalId}'
      location: location
      properties: {
        identityProvider: {
          type: 'Microsoft.EntraID'
          properties: {
            principalType: principalType
          }
        }
        roles: roles
      }
    }
    
  2. 部署 Bicep 範本以註冊主體:

    az deployment group create \
        --resource-group "<resource-group>" \
        --template-file register-principal.bicep \
        --parameters clusterName="<cluster-name>" principalId="<principal-id>"
    
  3. 列出使用 REST API 註冊的叢集所有主體(在 Bicep 部署後很有用):

    az rest \
        --method GET \
        --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.DocumentDB/mongoClusters/<cluster-name>/users?api-version=2025-09-01"
    
  4. 取得由 Bicep 建立的特定已註冊主體的詳細資訊 (取代 <principal-id>):

    az resource show \
        --resource-group "<resource-group>" \
        --name "<cluster-name>/users/<principal-id>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters/users" \
        --latest-include-preview
    
  5. 透過刪除資源移除主體 (或部署不包含該使用者資源的範本):

    az resource delete \
        --resource-group "<resource-group>" \
        --name "<cluster-name>/users/<principal-id>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters/users" \
        --latest-include-preview
    
  1. 喺 Azure portal 開啟目標 Azure DocumentDB 叢集。

  2. 選取 [設定] 下方的 [驗證]

  3. Microsoft Entra ID 認證 區塊中,入口網站依物件 ID 列出註冊的 Microsoft Entra 主體。 使用此檢視來:

    • 掃描清單尋找預期的物件識別碼。
    • 可選擇列出的條目(或使用入口網站的搜尋功能)查看單一主體的詳細資料。
    • 使用條目旁的 移除 動作,立即撤銷該主體的資料平面存取權。
  4. 要取得入口網站列表中物件識別碼的友善名稱,請使用 Microsoft Entra ID 區塊中的使用者頁面。 然後,依照物件 ID 或友名搜尋。

  1. 請使用以下指令之一取得您想授權存取的 Microsoft Entra 主體的唯一識別碼(物件 ID):

    • 目前登入身份

      az ad signed-in-user show      
      
    • 另一個以友善名稱識別的人類身份

      az ad user show \
        --id "<user-alias-and-domain>"
      
    • 使用應用程式識別碼的服務主體

      az ad sp show \
        --id "<application-id>"
      
    • 使用資源群組和名稱的受管理身份

      az identity show \
        --resource-group "<resource-group>" \
        --name "<managed-identity-name>"      
      
  2. 建立一個 Terraform 檔案(例如 register-principal.tf),使用 AzAPI 提供者來註冊主體並映射資料庫角色:

    variable "cluster_name" {
      type        = string
      description = "Name of the existing cluster"
    }
    
    variable "resource_group_name" {
      type        = string
      description = "Name of the existing resource group"
    }
    
    variable "principal_id" {
      type        = string
      description = "Object ID of the Microsoft Entra principal"
    }
    
    variable "principal_type" {
      type        = string
      description = "Type of principal: User, ServicePrincipal, or ManagedIdentity"
      default     = "User"
    }
    
    variable "roles" {
      type = list(object({
        db   = string
        role = string
      }))
      description = "Database roles to assign"
      default = [
        {
          db   = "sales"
          role = "readWrite"
        }
      ]
    }
    
    terraform {
      required_providers {
        azapi = {
          source  = "azure/azapi"
          version = "~> 2.0"
        }
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
    provider "azapi" {}
    
    data "azurerm_resource_group" "existing" {
      name = var.resource_group_name
    }
    
    data "azurerm_mongo_cluster" "existing" {
      name                = var.cluster_name
      resource_group_name = var.resource_group_name
    }
    
    resource "azapi_resource" "mongo_cluster_user" {
      type      = "Microsoft.DocumentDB/mongoClusters/users@2025-09-01"
      name      = var.principal_id
      parent_id = data.azurerm_mongo_cluster.existing.id
      location  = data.azurerm_resource_group.existing.location
    
      body = {
        properties = {
          identityProvider = {
            type = "MicrosoftEntraID"
            properties = {
              principalType = var.principal_type
            }
          }
          roles = var.roles
        }
      }
    }
    

    小提示

    欲了解更多 AzAPI 提供者資訊,請參閱 Azure AzAPI 提供者文件。

    • principalType替換為對於應用程式/服務主體的servicePrincipal或受管理的身分識別的ManagedIdentity
    • 要授予管理員權限,請在陣列中使用{"db":"admin","role":"root"}roles
  3. 建立一個名為 register-principal.tfvars 的變數檔案:

    cluster_name        = "<cluster-name>"
    resource_group_name = "<resource-group>"
    principal_id        = "<principal-id>"
    principal_type      = "User"
    roles = [
      {
        db   = "sales"
        role = "readWrite"
      }
    ]
    
  4. 初始化並套用 Terraform 設定來註冊使用者:

    terraform init --upgrade
    
    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform plan --var-file="register-principal.tfvars" --out "register-principal.tfplan"
    
    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform apply "register-principal.tfplan"
    
  5. 使用 REST API 列出叢集所有註冊的主體(在 Terraform 部署後很有用):

    az rest \
        --method GET \
        --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.DocumentDB/mongoClusters/<cluster-name>/users?api-version=2025-09-01"
    
  6. 取得由 Terraform 建立的特定已註冊主體的詳細資訊 (取代 <principal-id>):

    az resource show \
        --resource-group "<resource-group>" \
        --name "<cluster-name>/users/<principal-id>" \
        --resource-type "Microsoft.DocumentDB/mongoClusters/users" \
        --latest-include-preview
    
  7. 透過刪除 Terraform 資源移除主體:

    ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv) terraform destroy --var-file="register-principal.tfvars"
    

備註

Azure DocumentDB 叢集是由一個內建的管理原生 DocumentDB 使用者建立的。 叢集配置完成後,你可以 新增更多原生管理的 DocumentDB 使用者 。 新增到叢集的 Microsoft Entra ID 系統管理使用者,將會與同一叢集上定義的原生 DocumentDB 系統管理使用者共存。 所有管理的 Microsoft Entra ID 身份都會複製到資料庫中。

非管理性的 Microsoft Entra ID 身份會在資料庫中建立。 當你在資料庫中列出非管理使用者時,清單包含所有管理及非管理的 Microsoft Entra ID 身份,以及所有 次要(非管理)原生 DocumentDB 使用者

取得叢集認證

您可以使用連線 URI 或您慣用語言之驅動程式的自訂設定物件來連線到叢集。 在任一 選項中, 方案都必須設定為 mongodb+srv ,以連接到叢集。 主機位於 *.global.mongocluster.cosmos.azure.com*.mongocluster.cosmos.azure.com 網域,視您使用目前的叢集或全域讀寫端點而定。 +srv*.global.* 主機架構可確保即使發生 區域交換作業,您的用戶端仍會動態連接到多叢集配置中的適當可寫入叢集。 在單一叢集設定中,您可以不分辨地使用任一連接字串。

必須啟用 tls 設定。 其餘建議的設定是最佳做法組態設定。

Option 價值觀
scheme mongodb+srv
host <cluster-name>.global.mongocluster.cosmos.azure.com<cluster-name>.mongocluster.cosmos.azure.com
tls true
authMechanism MONGODB-OIDC
retrywrites false
maxIdleTimeMS 120000

這很重要

Azure 入口網站 取得連線字串。

  1. 請導航至 Azure DocumentDB 叢集。

  2. 選取 [ 連接字串 ] 導覽功能表選項。

  3. 複製或記錄 [連接字串] 欄位中的值。

    小提示

    Microsoft Entra ID 連接字串位於 Microsoft Entra ID 區段中。

在 MongoDB Shell 中使用 Microsoft Entra ID 進行連接

使用安裝 MongoDB Shell 的用戶端裝置,使用 Microsoft Entra ID 身份連接到你的 Azure DocumentDB 叢集。

  1. 在安裝了 MongoDB shell 的用戶端上開啟終端機。

  2. 取得你的 Azure DocumentDB 叢集 名稱 以及目標身份的 用戶端 ID

  3. 透過以下連接字串連接:

    mongosh "mongodb+srv://<client-id>@<cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=MONGODB-OIDC&retrywrites=false&maxIdleTimeMS=120000"
    

在 Visual Studio Code 中使用 Microsoft Entra ID 連接

使用 Visual Studio Code 搭配 DocumentDB 擴充功能 ,使用 Microsoft Entra ID 身份連接到你的 Azure DocumentDB 叢集。

這很重要

當你在 Visual Studio Code 中使用 Microsoft Entra ID 並搭配 DocumentDB 擴充功能對 Azure DocumentDB 叢集進行驗證時,shell 功能不支援。 如果你需要使用 MongoDB shell 搭配 Microsoft Entra ID 認證,請 直接在用戶端機器上使用 MongoDB Shell

  1. 開啟 Visual Studio Code。

  2. 請在側邊欄的 DocumentDB 延伸模組中瀏覽。

  3. 連接 區塊中,選擇 + 新連接...

  4. 在連線類型對話框中,選擇 連接字串

  5. 請使用以下連接串:

    mongodb+srv://<client-id>@<cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=MONGODB-OIDC&retrywrites=false&maxIdleTimeMS=120000
    
  6. 等待自動提示使用Microsoft Entra ID認證。 輸入符合你身份類型的相關憑證。

    備註

    例如,如果你用自己的身份(人類身份)登入,就使用無密碼認證體驗。

  7. 等連線完成後再說。 接著會在叢集的 連接 區塊新增一個新的 DocumentDB 項目。

使用 Microsoft Entra ID 在 MongoDB Compass 中連接

直接使用 MongoDB Compass 應用程式使用 Microsoft Entra ID 身份連接到你的 Azure DocumentDB 叢集。

  1. 開始使用 MongoDB Compass 應用程式。

  2. +」選單中選擇新增連線。

  3. 新連線對話框中切換「編輯連線字串」設定以啟用。

  4. 將以下連接字串輸入至 URI 輸入框。

    mongodb+srv://<client-id>@<cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=MONGODB-OIDC&retrywrites=false&maxIdleTimeMS=120000
    
  5. 現在, 打開進階連線選項 對話框。

  6. 一般 區段中,選擇 mongodb+srv連接字串方案

  7. 接著,進入 認證 區塊。

  8. 請確保已選擇 OIDC 選項。

  9. 現在,請前往 OIDC 選項 區塊。

  10. 請確保也選擇了 「考慮目標端點可信 」選項。

  11. 選取 [儲存並連線]。

管理 DocumentDB 次要 (非系統管理) Microsoft Entra ID 身分識別

請以管理員 Microsoft Entra ID 身份登入叢集,以執行非管理 Microsoft Entra ID 身份的管理操作。

備註

所有非管理使用者的管理指令均支援 SecurityPrincipaluser 主型別。

  1. 使用管理用的 Microsoft Entra ID 身份登入叢集,並使用像 MongoDB Shell 這類工具。

  2. 使用以下指令在叢集上新增一個非管理的 Microsoft Entra ID 身份,並具備createUser權限:

    db.runCommand(
      {
        createUser: "<entra-id-unique-identifier>",
        roles: [
          { role: "clusterAdmin", db: "admin" },
          { role: "readWriteAnyDatabase", db: "admin" }
        ],
        customData: { "IdentityProvider": { "type": "MicrosoftEntraID", "properties": { "principalType": "user" } } }
      }
    )
    
  3. 在叢集上新增具有 唯讀權限的非系統管理 Microsoft Entra ID 身分識別,使用 createUser 並指派不同的角色集。

    db.runCommand(
      {
        createUser: "<entra-id-unique-identifier>",
        roles: [
          { role: "readAnyDatabase", db: "admin" }
        ],
        customData: { "IdentityProvider": { "type": "MicrosoftEntraID", "properties": { "principalType": "user" } } }
      }
    )
    
  4. 用該 dropUser 指令從叢集中移除一個非管理的 Microsoft Entra ID 身份。

    db.runCommand(
      {
        dropUser: "<entra-id-unique-identifier>"
      }
    )
    
  5. 請使用 userInfo 列出叢集上所有 Microsoft Entra ID 和官方 DocumentDB 使用者。

    db.runCommand(
      {
        usersInfo: 1
      }
    )
    

    備註

    所有 Microsoft Entra ID 及原生 DocumentDB 管理使用者都會複製到資料庫中。 由於此複製,使用者清單包含叢集上所有管理及非管理的 Microsoft Entra ID 與原生 DocumentDB 使用者。

在程式碼中透過 Microsoft Entra ID 進行連接

請用應用程式碼和你偏好語言的適當用戶端函式庫,正確地核對存取權限。

class AzureIdentityTokenCallback(OIDCCallback):
    def __init__(self, credential):
        self.credential = credential

    def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult:
        token = self.credential.get_token(
            "https://ossrdbms-aad.database.windows.net/.default").token
        return OIDCCallbackResult(access_token=token)

clusterName = "<cluster-name>"

credential = DefaultAzureCredential()
authProperties = {"OIDC_CALLBACK": AzureIdentityTokenCallback(credential)}

client = MongoClient(
  f"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/",
  connectTimeoutMS=120000,
  tls=True,
  retryWrites=True,
  authMechanism="MONGODB-OIDC",
  authMechanismProperties=authProperties
)
const AzureIdentityTokenCallback = async (params: OIDCCallbackParams, credential: TokenCredential): Promise<OIDCResponse> => {
  const tokenResponse: AccessToken | null = await credential.getToken(['https://ossrdbms-aad.database.windows.net/.default']);
  return {
      accessToken: tokenResponse?.token || '',
      expiresInSeconds: (tokenResponse?.expiresOnTimestamp || 0) - Math.floor(Date.now() / 1000)
  };
};

const clusterName: string = '<cluster-name>';

const credential: TokenCredential = new DefaultAzureCredential();

const client = new MongoClient(
    `mongodb+srv://${clusterName}.global.mongocluster.cosmos.azure.com/`, {
    connectTimeoutMS: 120000,
    tls: true,
    retryWrites: true,
    authMechanism: 'MONGODB-OIDC',
    authMechanismProperties: {
        OIDC_CALLBACK: (params: OIDCCallbackParams) => AzureIdentityTokenCallback(params, credential),
        ALLOWED_HOSTS: ['*.azure.com']
    }
  }
);
string tenantId = "<microsoft-entra-tenant-id>";
string clusterName = "<cluster-name>";

DefaultAzureCredential credential = new();
AzureIdentityTokenHandler tokenHandler = new(credential, tenantId);

MongoUrl url = MongoUrl.Create($"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/");
MongoClientSettings settings = MongoClientSettings.FromUrl(url);
settings.UseTls = true;
settings.RetryWrites = false;
settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(2);
settings.Credential = MongoCredential.CreateOidcCredential(tokenHandler);
settings.Freeze();

MongoClient client = new(settings);

internal sealed class AzureIdentityTokenHandler(
    TokenCredential credential,
    string tenantId
) : IOidcCallback
{
    private readonly string[] scopes = ["https://ossrdbms-aad.database.windows.net/.default"];

    public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken)
    {
        AccessToken token = credential.GetToken(
            new TokenRequestContext(scopes, tenantId: tenantId),
            cancellationToken
        );

        return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow);
    }

    public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken)
    {
        AccessToken token = await credential.GetTokenAsync(
            new TokenRequestContext(scopes, parentRequestId: null, tenantId: tenantId),
            cancellationToken
        );

        return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow);
    }
}