Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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 existing Fabric capacity
- If you don't have Fabric capacity, start a Fabric trial.
An existing Cosmos DB database in Fabric
- If you don't have one already, create a new Cosmos DB database in Fabric.
An identity with the Read permission for the database in Fabric
- For more information on Fabric permissions, see access controls.
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.
Open the Fabric portal (https://app.fabric.microsoft.com).
Navigate to your existing Cosmos DB database.
Select the Settings option in the menu bar for the database.
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].
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)