Skip to main content

How to Connect to Azure Cosmos DB with Microsoft Entra ID in C#

· 11 min read
Jagdish Kumawat
Founder @ Dewiride

A .NET C# app can use Azure Cosmos DB without a single key: give the CosmosClient the account's URI and a Microsoft Entra ID credential, and every request carries a token instead. Here's the whole thing in a small console app, with real output and what each request cost.

The Azure Cosmos DB SDK for .NET, the Microsoft.Azure.Cosmos package, talks to an account through one object, the CosmosClient. It can authenticate with an account key or with Microsoft Entra ID. With Entra ID, the app signs in as an identity, your own account on your computer or a managed identity in Azure, and Cosmos DB checks that identity's data role. No secret lives in the app or its settings, and an account with key-based authentication turned off works the same.

Syntax​

Syntax
using CosmosClient <client> = new(
"<account-endpoint>",
<token-credential>,
new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = <json-serializer-options>,
});

Container <container> = <client>.GetContainer("<database-id>", "<container-id>");
PartWhat it is
<client>The client, one for the whole app. Microsoft's reference: CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application
<account-endpoint>The account's URI from its Overview, such as https://<account>.documents.azure.com:443/
<token-credential>A Microsoft Entra ID credential from the Azure.Identity package, such as new AzureCliCredential() on your computer
UseSystemTextJsonSerializerWithOptionsOptional. Stores your items with System.Text.Json and these options
<json-serializer-options>The System.Text.Json options for your items, such as JsonSerializerOptions.Web
GetContainer("<database-id>", "<container-id>")A Container to read and write items. The reference says it returns a proxy reference to a container, which doesn't guarantee existence

Creating the client doesn't connect to anything: creation doesn't make any network calls. A wrong URI or a missing role shows up at the first request.

The Example​

A small notes app keeps its notes in the container notes of the database notesdb, in the account cosmos-howto-4224. The container's partition key path is /id, so each note's ID is also its partition key. The console app saves two notes and reads one back, signed in with my Azure CLI account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.
  • The Azure CLI, signed in with az login. The app uses that sign-in.
  • A Cosmos DB data role for your account on the database or container, such as Cosmos DB Built-in Data Contributor. An Azure role such as Owner isn't enough.

Step 1: Create a Console App and Add the Packages​

Terminal
dotnet new console -n NotesApp
cd NotesApp
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/NotesApp/NotesApp.csproj:
Restore succeeded.

Then add three packages:

Terminal
dotnet add package Microsoft.Azure.Cosmos --version 3.64.0
dotnet add package Newtonsoft.Json --version 13.0.4
dotnet add package Azure.Identity --version 1.21.0

Each command ends like this one:

Output (the last lines of the first command)
info : PackageReference for package 'Microsoft.Azure.Cosmos' version '3.64.0' added to file '/Users/you/source/NotesApp/NotesApp.csproj'.
log : Restored /Users/you/source/NotesApp/NotesApp.csproj (in 734 ms).
  • Microsoft.Azure.Cosmos is the Cosmos DB SDK.
  • Newtonsoft.Json is there because the SDK needs it and leaves the version to you: without it, the build stops with an error from the SDK's own check (Fixed). Microsoft recommends 13.0.4 for this SDK version.
  • Azure.Identity has the Microsoft Entra ID credentials.

The project file now lists all three:

NotesApp.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>

</Project>

Open the folder in VS Code, or NotesApp.csproj in Visual Studio.

Step 2: Create the Client​

Replace everything in Program.cs with the client first:

Program.cs (the start)
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// Sign in with your Azure CLI account: no keys anywhere.
using CosmosClient client = new(
"https://cosmos-howto-4224.documents.azure.com:443/",
new AzureCliCredential(),
new CosmosClientOptions
{
// Store items with System.Text.Json and camelCase names, so the Id property is saved as "id".
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
  • The URI is the account's address. Use your own.
  • new AzureCliCredential() gets a token from the Azure CLI, the account you signed in with az login. The SDK asks it for a token whenever it needs one.
  • UseSystemTextJsonSerializerWithOptions stores your items with System.Text.Json. JsonSerializerOptions.Web writes property names in camelCase, so the record's Id becomes id. That matters: the id property is case-sensitive, and every item needs one.
  • using disposes the client when the program ends. A web app would register one client for its whole lifetime instead.

Step 3: Write and Read Notes​

Add the rest below it:

Program.cs (the rest)
Container notes = client.GetContainer("notesdb", "notes");

// Write two notes. The container's partition key path is /id, so each note's ID is also its partition key.
foreach (Note note in new[] { new Note("note-1", "Buy milk"), new Note("note-2", "Call the plumber") })
{
ItemResponse<Note> saved = await notes.UpsertItemAsync(note, new PartitionKey(note.Id));
Console.WriteLine($"Saved {note.Id}: {(int)saved.StatusCode} {saved.StatusCode}, {saved.RequestCharge} RU");
}

// Read one note back by its ID and partition key.
ItemResponse<Note> read = await notes.ReadItemAsync<Note>("note-1", new PartitionKey("note-1"));
Console.WriteLine($"Read {read.Resource.Id}: \"{read.Resource.Text}\", {read.RequestCharge} RU");

record Note(string Id, string Text);
  • GetContainer names the database and container.
  • UpsertItemAsync creates the item, or replaces it if one with that ID exists. The reference: creation or replace can be identified by the status code: 201 - item created 200 - item replaced.
  • new PartitionKey(note.Id) is the item's partition key value. The container is partitioned by /id, so it's the note's ID.
  • ReadItemAsync is a point read: one item by its ID and partition key, the cheapest way to read.
  • RequestCharge is what the request cost, in request units (RUs).
  • record Note is the item: an Id and a Text.

Step 4: Run It Twice​

Run dotnet run twice in VS Code's terminal, or press Ctrl+F5 twice in Visual Studio:

Output
$ dotnet run
Saved note-1: 201 Created, 5.9 RU
Saved note-2: 201 Created, 5.9 RU
Read note-1: "Buy milk", 1 RU

$ dotnet run
Saved note-1: 200 OK, 10.29 RU
Saved note-2: 200 OK, 10.29 RU
Read note-1: "Buy milk", 1 RU

macOS-style terminal window titled Terminal — NotesApp showing two runs of dotnet run: the first saves note-1 and note-2 with 201 Created at 5.9 RU each and reads note-1, Buy milk, for 1 RU; the second saves both with 200 OK at 10.29 RU each and reads note-1 again for 1 RU

The first run created both notes, 201 Created; the second replaced them, 200 OK. Replacing cost more than creating, 10.29 RU against 5.9, and the point read cost 1 RU both times. No key was involved: the account has key-based authentication turned off, and the app read and wrote as my Azure CLI account.

The Complete File​

macOS-style code window titled Program.cs — NotesApp showing the whole app: a CosmosClient created with the account URI, a new AzureCliCredential and System.Text.Json web options, a loop that upserts note-1 and note-2 with their IDs as partition keys and prints the status code and request charge, a point read of note-1, and the Note record with Id and Text

Program.cs
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// Sign in with your Azure CLI account: no keys anywhere.
using CosmosClient client = new(
"https://cosmos-howto-4224.documents.azure.com:443/",
new AzureCliCredential(),
new CosmosClientOptions
{
// Store items with System.Text.Json and camelCase names, so the Id property is saved as "id".
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});

Container notes = client.GetContainer("notesdb", "notes");

// Write two notes. The container's partition key path is /id, so each note's ID is also its partition key.
foreach (Note note in new[] { new Note("note-1", "Buy milk"), new Note("note-2", "Call the plumber") })
{
ItemResponse<Note> saved = await notes.UpsertItemAsync(note, new PartitionKey(note.Id));
Console.WriteLine($"Saved {note.Id}: {(int)saved.StatusCode} {saved.StatusCode}, {saved.RequestCharge} RU");
}

// Read one note back by its ID and partition key.
ItemResponse<Note> read = await notes.ReadItemAsync<Note>("note-1", new PartitionKey("note-1"));
Console.WriteLine($"Read {read.Resource.Id}: \"{read.Resource.Text}\", {read.RequestCharge} RU");

record Note(string Id, string Text);

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out Newtonsoft.Json because the app uses System.Text.JsonThe build stops with the SDK's Newtonsoft.Json checkReference Newtonsoft.Json 13.0.4 anyway
Saving a record with Id without camelCase optionsCosmos DB treats Id as an ordinary property, and the item has no idUse JsonSerializerOptions.Web, or name the JSON property id
Creating a new CosmosClient for every requestEach client manages its own connections, and the app loses the reuse that one client givesCreate one and reuse it for the app's lifetime
Giving your account an Azure role, such as Contributor, and expecting data accessRequests are blocked: Azure roles don't include Cosmos DB dataGive it a Cosmos DB data role

Troubleshooting​

SymptomLikely causeFix
CosmosException … Forbidden (403); Substatus: 5301 … Request blocked by AuthYour identity has no data role on that database or container (Fixed)Assign one, as in How to Give Your Account Access to Azure Cosmos DB Data with the Azure CLI
error The Newtonsoft.Json package must be explicitly referenced with version >= 10.0.2 at build timeNo Newtonsoft.Json reference (Fixed)dotnet add package Newtonsoft.Json --version 13.0.4
AzureCliCredential fails to get a tokenYou're not signed in to the Azure CLI, or the sign-in expiredRun az login again

FAQ​

What credential does the app use in Azure?​

A managed identity, with ManagedIdentityCredential from the same Azure.Identity package. Give that identity its own Cosmos DB data role; nothing else in the code changes.

Can I use DefaultAzureCredential instead?​

Yes. It tries several credentials in turn, including the Azure CLI and managed identity. AzureCliCredential is the direct choice when you know the app runs on your computer with your sign-in; to keep DefaultAzureCredential and still use only the Azure CLI locally, see How to Make DefaultAzureCredential Use Only the Azure CLI with AZURE_TOKEN_CREDENTIALS.

Conclusion​

To connect to Azure Cosmos DB with Microsoft Entra ID in C#, create one CosmosClient with the account's URI and a TokenCredential such as AzureCliCredential, and give the identity a Cosmos DB data role. Reference Newtonsoft.Json 13.0.4 even with System.Text.Json, store items with JsonSerializerOptions.Web so Id becomes id, and use UpsertItemAsync and ReadItemAsync with the item's partition key.

Additional Resources​