, Mark Joseph Colibao, home

Use Cosmos DB from .NET with roles, not keys

Assign a Cosmos DB data role, connect with DefaultAzureCredential, then turn off key access.

Written 2 min read

A Cosmos DB account key is a secret you have to store, rotate and keep out of source control. A key or connection string committed to a repo is the most common way Cosmos DB credentials leak.

Cosmos DB has its own data-plane roles that work with Microsoft Entra ID. Give the app one of those, connect with a token, and turn the keys off.

Why it's different from other services

For most Azure services, data access is a normal Azure role (az role assignment create). Cosmos DB for NoSQL keeps its data roles separate:

  • Control plane (Azure roles): create and delete accounts, databases and containers.
  • Data plane (Cosmos roles): read and write items.

The built-in data roles are Cosmos DB Built-in Data Reader (00000000-0000-0000-0000-000000000001) and Cosmos DB Built-in Data Contributor (00000000-0000-0000-0000-000000000002). Creating databases and containers is a control-plane job, so the app's data role doesn't cover it. That split is useful: the app reads and writes items, and the deploy script creates containers. Even the Azure role Cosmos DB Operator, made for managing accounts, can't read the data or the keys.

Who can do what in a Cosmos DB for NoSQL account
ActionBuilt-in Data ReaderCosmos data roleBuilt-in Data ContributorCosmos data roleCosmos DB OperatorAzure role
Read items and run queriesYesYesNo
Create, replace and delete itemsNoYesNo
Create databases and containersNoNoYes
Read or regenerate the account keysNoNoNo

1. Assign the data role

bash
PRINCIPAL=<managed-identity-principal-id>

az cosmosdb sql role assignment create \
  --account-name <account> \
  --resource-group <resource-group> \
  --role-definition-id 00000000-0000-0000-0000-000000000002 \
  --principal-id "$PRINCIPAL" \
  --scope "/"

--scope "/" covers the whole account. To limit it to one container, use /dbs/<database>/colls/<container>.

Do the same for your own account, so the code also works on your laptop. Use the object ID from az ad signed-in-user show --query id -o tsv.

2. Connect with DefaultAzureCredential

C#
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// One client per app, as the SDK recommends.
builder.Services.AddSingleton(_ => new CosmosClient(
    builder.Configuration["Cosmos:Endpoint"], // https://<account>.documents.azure.com:443/
    new DefaultAzureCredential(),
    new CosmosClientOptions
    {
        UseSystemTextJsonSerializerWithOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web),
    }));

The only setting is the endpoint, and it isn't a secret.

3. Create containers outside the app

When the app signs in with Entra ID, the SDK's create, replace and delete methods for databases and containers fail with a 403, because they are control-plane work. So don't call CreateContainerIfNotExistsAsync from the app. Create containers in your deploy script, which runs with your own rights:

bash
az cosmosdb sql container create -a <account> -g <resource-group> \
  -d <database> -n orders --partition-key-path /customerId

4. Turn off key access

Once nothing uses a key, switch keys off for the whole account:

bash
az resource update --resource-type "Microsoft.DocumentDB/databaseAccounts" \
  -n <account> -g <resource-group> --set properties.disableLocalAuth=true

From now on, every request has to come with an Entra token. Old connection strings stop working.

Check that it works

  • database.ReadAsync() reads only the database's metadata, which both built-in data roles allow. It proves the endpoint, the sign-in and the role in one call.
  • On a 403, list the assignments with az cosmosdb sql role assignment list and check the principal ID and the scope.
  • Once keys are off, the Data Explorer in the Azure portal sends data requests with your Entra ID sign-in by default, so your user needs a data role as well.

Sources