Tuesday, 22 July 2025

Use DefaultAzureCredential with C# to Work with Azure Cosmos DB Data Using "Cosmos DB Built-in Data Contributor" RBAC

 We have discussed "Add Cosmos DB Built-in Roles to Resource Identities via Terraform to Allow Role Based Access to Data in Cosmos DB" in the previous post. Now that the data constributor roles are setup in Azure Cosmos DB, let's look at how to write a simple code to access,  create Cosmos DB data using DefaultAzureCredential with C#.

The expection is to get document data created in Cosmos DB as similar to shown below.



Let's look at the step by step how we can use DefaultAzureCredential to work with Cosmos DB data.

First we need to refe to below NuGet packages. We need to refer Newtonsoft.Json as it is a prerequisite for Microsoft.Azure.Cosmos .

<ItemGroup>
    <PackageReference Include="Azure.Identity" Version="1.14.2" />
    <PackageReference Include="Microsoft.Azure.Cosmos" Version="3.52.1" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  </ItemGroup>

Then we can create DefaultAzureCredential and create aconnection to Cosmos DB as shown below.

// Credential class for testing on a local machine or Azure services
TokenCredential credential = new DefaultAzureCredential(
                new DefaultAzureCredentialOptions
                {
                    TenantId = "azure_tenatid"
                });

// New instance of CosmosClient class using a connection string
CosmosClient cosmosClient = new(
    accountEndpoint: "https://ch-px-dev-eus-001-cdb.documents.azure.com:443/",
    tokenCredential: credential
);

 Using the connection we can access a database and contianer in the Cosmos account.

Database cosmodDb = cosmosClient.GetDatabase("px");
Container cosmosContainer = cosmodDb.GetContainer("tenants");

await cosmosContainer.CreateItemAsync(
    item: new
    {
        id = "test-item-id",
        name = "Test Item",
        description = "This is a test item created using DefaultAzureCredential.",
        partition = "test-item-partion-key", // 👈 This is required
    },
    partitionKey: new PartitionKey("test-item-partion-key")
);

Then we can dispose the connection.

cosmosClient.Dispose();

Note that here the best practices like DI etc are not considered. The purpose was to show how to create a Cosmos DB account connection with DefaultAzureCredential. In real projects you should consider best practices to implement a singleton connection for Cosmos DB account. Full example code used in this post is available in GitHub.

 

No comments:

Post a Comment