Search documentationEsc

Authentication

Authenticate against Azure Cosmos DB with a connection string or a TokenCredential identity (RBAC).

Cosmos Repository supports both connection-string and identity-based authentication. The right choice usually depends on whether you have control-plane access to assign role-based access control (RBAC) roles to a managed identity.

Connection string

The simplest setup. Set RepositoryOptions.CosmosConnectionString and the SDK will use it for both control- and data-plane operations.

builder.Services.AddCosmosRepository(options =>
{
options.CosmosConnectionString = "<connection string>";
options.DatabaseId = "samples";
options.ContainerId = "data-store";
});

Identity (TokenCredential)

The Azure Cosmos DB .NET SDK also supports authenticating with a TokenCredential. Identities (users, groups, application registrations, or managed identities) are typically preferred from an audit and least-privilege perspective.

You will need to set both AccountEndpoint and TokenCredential on RepositoryOptions:

  1. Create the identity in Microsoft Entra ID if it doesn’t already exist.

  2. Use the Azure CLI to assign a Cosmos DB data-plane role to the identity at the desired scope. Built-in roles are usually sufficient; see the list of built-in role definitions.

  3. Configure your application to pass the credential:

    using Azure.Identity;
    using Microsoft.Azure.CosmosRepository;
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddCosmosRepository(options =>
    {
    options.TokenCredential = new DefaultAzureCredential();
    options.AccountEndpoint = new Uri("<account endpoint URI>");
    options.ContainerId = "data-store";
    options.DatabaseId = "samples";
    });

DefaultAzureCredential from the Azure.Identity NuGet package picks the right credential for each environment (Visual Studio, CLI, managed identity, environment variables, …). See the Azure Identity overview for details.

When to choose which

ScenarioRecommendation
Local prototype, sandbox keyConnection string
Azure-hosted production appDefaultAzureCredential + RBAC role assignment
CI/CD secrets-free buildWorkload Identity Federation + DefaultAzureCredential
Multi-tenant app per-tenant identityBuild a ChainedTokenCredential and inject it