How to connect to Cosmos DB for Mongo using managed identity

Flavio Duarte 20 Reputation points
2025-07-31T14:52:25.6+00:00

I deployed Cosmos DB for Mongo and I can connect using the connection string in Python (for instance).

Now I'd like to connect using a user managed identity similar to it is done with Object Storage:

cred = DefaultAzureCredentials()
client = MongoClient(account_url=url, credential=cred) # should MongoClient for CosmosDB

I couldn't make this simple code work, despite have assigned "DocumentDB Account Contributor" to my user managed identity, which has more privileges that I wanted since it has control plane privileges and not just data plane.

I have tried variations of the above code based on what I found out there without success. At some point I got this error that kinda tells me it is possible to do what I'm trying to do:
To connect to Azure Cosmos DB for MongoDB (RU-based account) using a Managed Identity, you'll need to use Azure AD-based authentication instead of the traditional connection string with a username/password. As of mid-2024, Azure Cosmos DB for MongoDB vCore supports Azure AD-based authentication, but MongoDB API (RU-based) support is more limited and requires extra configuration.

Could you help with an example (python) connecting to Cosmos DB for Mongo along with the setup steps that need to be done?

Regards,

Flavio Duarte

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
{count} votes

Accepted answer
  1. Mahesh Kurva 6,850 Reputation points Microsoft External Staff Moderator
    2025-07-31T16:29:35.82+00:00

    Hi Flavio Duarte,

    Greetings!!

    Azure Cosmos DB for MongoDB vCore using a User Assigned Managed Identity in Python

    • Use Cosmos DB for MongoDB vCore, not RU-based.
    • Enable Microsoft Entra ID authentication on the cluster.
    • Assign dbOwner role to the Managed Identity in Entra ID.
    • UseDefaultAzureCredential() in your Python app.
    • Implement OIDC callback .

    For more information, please refer the documents:

    Build a Python console app with Azure Cosmos DB for MongoDB vCore

    Microsoft Entra ID authentication with Azure Cosmos DB for MongoDB vCore.

    Hope this helps. Do let us know if you any further queries.

    If this answers your query, do click Accept Answer and Yes for was this answer helpful. And, if you have any further query do let us know.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.