Inako
Inako

Reputation: 399

Azure Cosmos MongoDB API with Azure Managed Identities

I have an App Service in Azure connects to Azure Cosmos Mongo API using Connection String. I am wondering if there is a way to use Managed Identity to connect to Mongo API instead of using Connection String. I know that it is doable for Cosmos SQL API, but couldn't find any info regarding the Mongo API.

Thank you

Upvotes: 5

Views: 2574

Answers (3)

Pradeep
Pradeep

Reputation: 767

If you're using the Azure.ResourceManager.CosmosDB package, you can retrieve the keys using this code:

ArmClient armClient = new ArmClient(new ManagedIdentityCredential(clientId: managedIdentityClientId));
CosmosDBAccountResource accountResource = armClient.GetCosmosDBAccountResource(new ResourceIdentifier("/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.DocumentDB/databaseAccounts/<cosmos-db-account>"));
CosmosDBAccountKeyList keys = accountResource.GetKeys().Value;
string primaryMasterKey = keys.PrimaryMasterKey;

Upvotes: 0

sschmeck
sschmeck

Reputation: 7685

The solution for SQL API, described at Use system-assigned managed identities to access Azure Cosmos DB data can also be applied to the MongoDB API via querying the Access Key. The code for a Node Function App would need the packages @azure/identity, @azure/arm-cosmosdb and mongodb.

import { MongoClient } from 'mongodb';
import { ManagedIdentityCredential } from '@azure/identity';
import { CosmosDBManagementClient } from '@azure/arm-cosmosdb';

async function initializeClient(): Promise<MongoClient> {
  const subscriptionId = ...;
  const resourceGroupName = ...;
  const cosmosDbUrl = ...;
  const accountName = ...;

  const armClient = new CosmosDBManagementClient(
    new ManagedIdentityCredential(), subscriptionId
  );
  const { primaryMasterKey } = await armClient.databaseAccounts.listKeys(
    resourceGroupName, accountName
  );
  return MongoClient.connect(
    cosmosDbUrl,
    { auth: { username: accountName, password: primaryMasterKey } }
  );
}

The Managed Identity of the Function App requires the permission Microsoft.DocumentDB/databaseAccounts/listKeys/action. Therefore you can assign the role DocumentDB Account Contributor to the Managed Identity. See also Azure role-based access control in Azure Cosmos DB.

Upvotes: 0

Richard Szalay
Richard Szalay

Reputation: 84744

The intended pattern is to grant access to retrieve the keys via Managed Identity, and then the application uses that access to obtain the keys and connect via normal means. You'd need to come up with your own pattern to detect recycling of primary/secondary keys and switch accordingly.

The DocumentDB Account Contributor role provides access to the read/write keys via the List Keys API

The Cosmos DB Account Reader Role role provides access to the read only keys via the List Read Only Keys API

Upvotes: 1

Related Questions