Leverage the power of Azure CosmosDB in a Single-Page-Application with MSAL authentication using the CosmosDBClient

I am facing a challenge in connecting to an Azure CosmosDB using my Azure AD credentials from a Single-Page-Application.

  • My SPA has a functional login system, ensuring that users are logged in.
  • In Azure, I have successfully registered an app with the scope "Azure Cosmos DB" and "user_impersonation".
  • Within CosmosDB, there exists a role that grants read/write access to a specific database for an AD group.

Although everything seems to be set up correctly, I am struggling to create the CosmosDB client in JavaScript.

const cosmosClient = new CosmosClient({
        "https://my-service.my-ressource.azure.com:443",
        // The issue lies in setting my credentials here. I possess a valid JWT token, but it is not working.
       // key: myJwtAccessToken, // not working!
       // aadCredentials: new InteractiveBrowserCredential() // not working!
    });

Unfortunately, I lack the understanding of how to make this work properly.

The cosmosClient instance remains non-functional without a key.

Answer №1

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
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

This error occurs when trying to iterate over a property that is undefined (specifically, the 'forEach' property)

I am working on a project that involves integrating the Youtube API. The goal is to allow users to search for videos and display search results as they type. However, I only have experience with Python and Django, so I followed a tutorial to add AJAX funct ...

What is the best way to trigger a function in Vue.js when a click event occurs on Google Maps?

In my Nuxt.js app in SPA mode, I am utilizing the Google Maps API and I'm aiming to trigger a function in Vue.js methods from the gmap click event. When attempting this.createInfoWindow(), it became apparent that this does not refer to the VueCompone ...

"Organizing a menu in JSON format based on alphabetical

After following this guidance, I successfully created a JSON menu. However, the items are currently sorted by ID and I am in need of sorting them alphabetically. I am unsure about whether using array.sort(); would be applicable in this scenario. Check out ...

Having issues with Jquery and duplicating tables functionality not functioning as expected

I am facing an issue with two external jQuery files. One file allows me to clone the last row of a table, while the other is supposed to retrieve the id of a select tag based on a class assigned to it. However, the second script only works for the original ...

"Troubleshooting: jQuery functionality not functioning within the body of an Angular

Currently, I am utilizing jQuery to load gapi for my application's functionality in order to allow users to log out using their Google+ account. Although I have loaded jQuery in the head section of my index.html file, it appears that it is not being r ...

Navigating through directories (including nested ones) containing images in React Native; what's the best way to approach this

I am currently attempting to organize groups of images. Within the directory ./assets, there are several folders structured as follows: ./assets ├── 1x3 │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── 3x3 ├── 1. ...

A guide on implementing the stencilFunc method in Three.js

Is it possible to utilize stencilFunc and stencilOp functions within Three.js? I attempted to incorporate code for a stencil test but encountered issues. var scene = new THREE.Scene(); var renderer = new THREE.WebGLRenderer({ antialias: true, st ...

Is there a way to automatically populate my form with data depending on the value selected in a dropdown menu?

I'm facing an issue with prefilling a form based on the selected value from a dropdown menu that loads invoice IDs from my database. The problem arises when trying to populate the form fields using the data corresponding to the selected invoice ID. Th ...

Retrieve the package.json file for a specific package by making an HTTP request to public repositories

I’ve been searching online but haven’t found a satisfying answer to my question yet. My main objective is to generate a dependency tree for a particular npmjs library of a specific version, like retrieving the dependency tree for the angular library v ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

Prevent accidental deletion of the entire document in mongoose (express.js) by selectively removing only a specific string from an array

Hey there, I'm new to this platform and my English isn't great, so apologies if I don't grasp all the nuances of my issue. I have a question about why the findOneAndDelete() method in Mongoose is deleting all documents instead of just delet ...

What is the best way to merge two values with the same property in an object using a comma as a separator

Is it possible to combine the values of properties with a separator in my scenario? Here is an example of my JSON structure: { "name": "aa", "name": "bb", "name1": "cc", "name2": "dd" } I am looking to display the values of the key 'name&apo ...

When clicking on the dress in the masque, how do I change the attire so that it is instantly applied to the masque?

$("#tail").kendoFlatColorPicker({ preview: false, value: "#000", change: select }); $("#head").kendoFlatColorPicker({ preview: false, value: "#e15613", change: select }); I implemented the color ...

What is the best way to assign a unique ID to every element in this situation?

Here is the given code: var words = ['ac', 'bd', 'bf', 'uy', 'ca']; document.getElementById("wordTable").innerHTML = arr2tbl(2); function arr2tbl(ncols) { return words.reduce((a, c, i) => { ...

How can I achieve a smooth transition effect for an image using JavaScript

Hey there! I'm currently working on a project where I have multiple buttons that, when hovered over, change the background-image of a specific div. However, instead of the images suddenly appearing on the screen, I would like them to fade in gradually ...

What is the best way to retrieve the distinct number within an ng-repeat loop?

Utilizing angular ng-repeat to display the bootstrap tab, I have nested tabs within one another. In order to assign a unique id to both the tab element and its content, I am currently using $index as a way to achieve this. However, it proves ineffective wh ...

Converting HTML tables into arrays

I have JSON content that needs to be transformed into an array, specifically from a HTML table with cell values. Those cells should be combined into a single array for further use in the project. Struggling with the conversion of cell values into an arra ...

How can JavaScript be used to toggle the visibility of text on a webpage

Can anyone help me with a problem I'm having toggling text? I have a truncated text and I want to be able to switch back and forth between the truncated text and the original text on button click. Here is a link to the pen. var myButton = documen ...

The Angular app.component.html is failing to display the newly added component

Having some trouble rendering my new component in the browser. I've set up a fresh project using the Angular CLI and created a component named list-employees. Upon running ng serve -o, the project compiles without errors, but the browser displays a b ...

javascript show and hide navigation bar

I am currently working on a HTML menu that includes a button to open it and an unordered list : <nav class="menu"> <button> <h1>Menu</h1> </button> <ul class="mylist" ...