Accessing Azure CosmosDB using Azure AD credentials in a Single-Page-Application.
A summary of the steps taken:
Imported necessary modules from the @azure/cosmos
and @azure/identity
packages through import statements.
Utilized a ClientSecretCredential for authenticating with Azure
, enabling communication with Azure Cosmos DB
.
Created an instance of ClientSecretCredential containing tenant ID, client ID, and client secret for Azure AD authentication token retrieval.
Initialized a new CosmosClient
instance while passing endpoint and AADCredentials
to authenticate with Azure Cosmos DB.
Accessed the specified database and container within a Try block using the database
and container
objects.
Performed actions on the container such as reading all items with
container.items.readAll().fetchAll()
, logging the retrieved items to console.
Assigned roles to applications under the cosmos DB account using the command
az cosmosdb sql role assignment create -a <cosmosdbname> -g <rgname> -s "/" -p <service_principal_ID> -d 00000000-0000-0000-0000-000000000002
.
import { CosmosClient } from "@azure/cosmos";
import { ClientSecretCredential } from "@azure/identity";
// Configuration for Azure Cosmos DB and Azure AD application
const endpoint = "*****";
const tenantId = "*****";
const clientId = "*****";
const clientSecret = "*****";
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
const client = new CosmosClient({ endpoint, aadCredentials: credential });
const databaseId = "newDb";
const containerId = "insertCont";
async function main() {
try {
const database = client.database(databaseId);
const container = database.container(containerId);
const { resources: items } = await container.items.readAll().fetchAll();
console.log("Items in the container:");
items.forEach((item) => console.log(item));
} catch (error) {
console.error("Error:", error);
}
}
main();
Output:
Items in the container:
{
id: '1',
name: 'Item 1',
description: 'Description for Item 1',
_rid: 'gKQGAPaTgK4BAAAAAAAAAA==',
_self: 'dbs/gKQGAA==/colls/gKQGAPaTgK4=/docs/gKQGAPaTgK4BAAAAAAAAAA==/',
_etag: '"7a02bca3-0000-0700-0000-650e89be0000"',
_attachments: 'attachments/',
_ts: 1695451582
}
{
id: '2',
name: 'Item 2',
description: 'Description for Item 2',
_rid: 'gKQGAPaTgK4CAAAAAAAAAA==',
_self: 'dbs/gKQGAA==/colls/gKQGAPaTgK4=/docs/gKQGAPaTgK4CAAAAAAAAAA==/',
_etag: '"7a029ba7-0000-0700-0000-650e89d70000"',
_attachments: 'attachments/',
_ts: 1695451607
}