You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用托管身份认证Azure Cosmos DB MongoDB账户?C#尝试未果求助

Azure Cosmos DB MongoDB API 托管身份认证解决方案

Azure Cosmos DB MongoDB API 支持使用托管身份进行身份认证,你当前的问题主要和MongoDB.Driver版本及配置步骤有关,以下是具体说明和解决方案:

版本要求

你使用的MongoDB.Driver 2.19.0版本不支持Azure AD托管身份认证,必须升级到2.20.0及以上,该版本才正式引入了对Azure AD身份验证(包括托管身份)的支持。

前置Azure配置

  • 为你的托管身份(系统分配或用户分配类型)在Azure门户中分配Cosmos DB的内置数据角色,例如Cosmos DB Built-in Data Contributor,确保该身份拥有目标数据库/集合的读写权限。
  • 确认Cosmos DB账户已启用Azure AD身份验证(默认启用,无需额外操作)。

C#代码实现

升级Driver版本后,使用以下代码配置托管身份认证,无需再依赖包含密钥的连接字符串:

using MongoDB.Driver;
using MongoDB.Driver.Core.Authentication;
using Azure.Identity;
using MongoDB.Bson;

// 替换为你的Cosmos DB MongoDB终结点和数据库名
var cosmosEndpoint = "https://your-cosmos-account.mongo.cosmos.azure.com:10255/";
var dbName = "your-target-db";

var clientSettings = new MongoClientSettings
{
    Server = new MongoServerAddress(new Uri(cosmosEndpoint).Host, new Uri(cosmosEndpoint).Port),
    Credential = MongoCredential.CreateAzureCredential(
        tenantId: null,
        userName: null,
        password: null,
        azureCredential: new DefaultAzureCredential()
    ),
    SslSettings = new SslSettings { EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 },
    UseTls = true
};

var mongoClient = new MongoClient(clientSettings);
var database = mongoClient.GetDatabase(dbName);

// 读写操作示例
var collection = database.GetCollection<BsonDocument>("your-collection");
var sampleDoc = new BsonDocument("name", "test");
collection.InsertOne(sampleDoc);

var retrievedDoc = collection.Find(Builders<BsonDocument>.Filter.Eq("name", "test")).FirstOrDefault();

代码说明

  • DefaultAzureCredential会自动适配运行环境:本地开发时使用Azure CLI/VS的登录身份,部署到Azure后自动使用配置的托管身份。
  • 无需指定租户ID、用户名或密码,托管身份的凭据会由Azure环境自动注入。

常见排查点

  • 角色分配生效存在延迟,配置后等待5-10分钟再测试。
  • 确认应用运行环境(如App Service、VM)已正确启用托管身份,且该身份未被限制访问Cosmos DB(如VNet防火墙规则)。
  • 检查Driver版本是否确实升级到2.20.0及以上,可通过NuGet包管理器确认。

内容的提问来源于stack exchange,提问作者Mallikarjuna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 10:05:03