Edit

Share via


Authenticate to Cosmos DB in Microsoft Fabric from Fabric Notebooks

Cosmos DB in Microsoft Fabric exclusively relies on Microsoft Entra ID authentication and built-in data plane roles to manage authentication and authorization. In this guide, you use Microsoft Entra ID and your signed-in account to connect to a Cosmos DB artifact in Microsoft Fabric.

Prerequisites

  • An identity with the Read permission for the database in Fabric

Retrieve Cosmos DB endpoint

First, get the endpoint for the Cosmos DB database in Fabric. This endpoint is required to connect using the Azure SDK.

  1. Open the Fabric portal (https://app.fabric.microsoft.com).

  2. Navigate to your existing Cosmos DB database.

  3. Select the Settings option in the menu bar for the database.

    Screenshot of the 'Settings' menu bar option for a database in the Fabric portal.

  4. In the settings dialog, navigate to the Connection section. Then, copy the value of the Endpoint for Cosmos DB NoSQL database field. You use this value in later step[s].

    Screenshot of the 'Connection' section of the 'Settings' dialog for a database in the Fabric portal.

Authenticate from a notebook

Fabric notebooks don't have a way to create a valid Azure credential object used by Azure services. Users authenticate using Fabric NotebookUtils credential utilities which requires the authentication scope for Cosmos DB and produces a token in string format. This requires some custom code to create a valid Azure credential object.

Here's a notebook sample that demonstrates how to do this.

Cell [1]:

#Install packages
%pip install azure-cosmos

Cell [2]:

#Imports and config values
import logging

from azure.cosmos.aio import CosmosClient
from azure.cosmos.exceptions import CosmosHttpResponseError

COSMOS_ENDPOINT = 'https://my-cosmos-endpoint.cosmos.fabric.microsoft.com:443/'
COSMOS_DATABASE_NAME = '{your-cosmos-artifact-name}'
COSMOS_CONTAINER_NAME = '{your-container-name}'

The contents of Cell 3 creates a FabricTokenCredential() object and contains the code necessary to produce a valid credential object for the Cosmos DB SDK from the token string generated by the Fabric NotebookUtils credential utilities which is required to authenticate a user.

Cell [3]:

# Custom TokenCredential implementation for Fabric authentication in a notebook
%pip install azure-core
from azure.core.credentials import TokenCredential, AccessToken
import base64
import json
import notebookutils
from datetime import datetime, timezone

class FabricTokenCredential(TokenCredential):

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None,
                  enable_cae: bool = False, **kwargs: Any) -> AccessToken:
        access_token = notebookutils.credentials.getToken("https://cosmos.azure.com/")
        parts = access_token.split(".")
        if len(parts) < 2:
            raise ValueError("Invalid JWT format")
        payload_b64 = parts[1]
        # Fix padding
        padding = (-len(payload_b64)) % 4
        if padding:
            payload_b64 += "=" * padding
        payload_json = base64.urlsafe_b64decode(payload_b64.encode("utf-8")).decode("utf-8")
        payload = json.loads(payload_json)
        exp = payload.get("exp")
        if exp is None:
            raise ValueError("exp claim missing in token")
        return AccessToken(token=access_token, expires_on=exp) 

Cell [4]:

# Create a Cosmos client with the FabricTokenCredential() and run a query
async with CosmosClient(endpoint, credential=FabricTokenCredential()) as client:
    container = client.get_database_client(COSMOS_DATABASE_NAME).get_container_client(COSMOS_CONTAINER_NAME)

    query_text = "SELECT * FROM c"

    results = container.query_items(query=query_text)

    items = []
    async for item in results:
        items.append(item)

    for item in items:
        print(item)