---
layout: Conceptual
title: Azure Cosmos DB Shell Security Best Practices - Azure Cosmos DB | Microsoft Learn
canonicalUrl: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/security
uhfHeaderId: MSDocsHeader-NoSQL
permissioned-type: public
recommendations: true
recommendation_types:
- Training
- Certification
breadcrumb_path: ../../breadcrumb/azure-nosql/toc.json
feedback_system: Standard
feedback_product_url: https://feedback.azure.com/d365community/forum/3002b3be-0d25-ec11-b6e6-000d3a4f0858
feedback_help_link_url: /answers/tags/187/azure-cosmos-db/
feedback_help_link_type: get-help-at-qna
ms.service: azure-cosmos-db
ms.subservice: nosql
ms.reviewer: mjbrown
ms.author: sasinnat
author: sajeetharan
description: Learn security best practices for using Azure Cosmos DB Shell including authentication, credential management, RBAC, and data protection.
ms.topic: article
ms.date: 2026-10-19T00:00:00.0000000Z
ai-usage: ai-assisted
locale: en-us
document_id: dfea90cf-e9a3-e31c-0e0f-f42abacae3a0
document_version_independent_id: dfea90cf-e9a3-e31c-0e0f-f42abacae3a0
updated_at: 2026-10-29T12:08:00.0000000Z
original_content_git_url: https://github.com/MicrosoftDocs/nosql-docs-pr/blob/live/azure/cosmos-db/shell/security.md
gitcommit: https://github.com/MicrosoftDocs/nosql-docs-pr/blob/d544fbd677e5c098756dbf81dcc8b6ff167255c1/azure/cosmos-db/shell/security.md
git_commit_id: d544fbd677e5c098756dbf81dcc8b6ff167255c1
site_name: Docs
depot_name: Learn.azure-nosql
page_type: conceptual
toc_rel: ../toc.json
word_count: 1386
asset_id: cosmos-db/shell/security
moniker_range_name: 
monikers: []
item_type: Content
source_path: azure/cosmos-db/shell/security.md
cmProducts:
- https://authoring-docs-microsoft.poolparty.biz/devrel/cd668c2f-f5b3-4573-8ad1-019570e3e2db
- https://authoring-docs-microsoft.poolparty.biz/devrel/68ec7f3a-2bc6-459f-b959-19beb729907d
- https://authoring-docs-microsoft.poolparty.biz/devrel/fcc3cd4a-59ea-47a2-9cc1-784142a5a25d
spProducts:
- https://authoring-docs-microsoft.poolparty.biz/devrel/cc82e69d-afbe-4554-9f4c-6705fc860c42
- https://authoring-docs-microsoft.poolparty.biz/devrel/90370425-aca4-4a39-9533-d52e5e002a5d
- https://authoring-docs-microsoft.poolparty.biz/devrel/d7a55faf-a992-4e27-aa3a-eadc9830e778
platformId: 7924edb1-a81d-e224-87ff-af7b8d910eef
---

# Azure Cosmos DB Shell Security Best Practices - Azure Cosmos DB | Microsoft Learn

Secure your Azure Cosmos DB Shell deployments with these comprehensive security best practices.

## Authentication methods

### 1. Microsoft Entra ID (recommended)

**Best for:** Development, testing, and production environments

**Advantages:**

- Most secure authentication method
- No credentials stored locally
- Automatic token refresh
- Supports multifactor authentication (MFA)
- Full audit trail in Azure

**Implementation:**

When launched without connection arguments, Cosmos DB Shell starts disconnected. Authenticate by connecting to your account endpoint with Microsoft Entra ID:

```bash
cosmosdbshell
CS > connect https://<account-name>.documents.azure.com:443/ --tenant=<tenant-id>
```

The browser opens for Azure sign-in after you run `connect`. Complete the flow and the shell uses your Microsoft Entra ID credentials.

**Configuration:**

```bash
connect <account_endpoint> --tenant=<tenant-id>
```

**Security Benefits:**

- Credentials never stored on disk
- Tokens automatically refreshed
- MFA provides additional protection
- RBAC controls what you can access

### 2. Managed identity (production)

**Best for:** Azure-hosted applications and production environments

**Advantages:**

- No credential management required
- Automatic token refresh
- Works with Azure services (App Service, Functions, AKS)
- No secrets to rotate
- Enhanced security in Azure

**Implementation:**

Enable managed identity on Azure resource:

**For App Service:**

```json
{
  "identity": {
    "type": "SystemAssigned"
  }
}
```

**From your terminal:**

```bash
cosmosdbshell --connect https://<account-name>.documents.azure.com:443/ --connect-managed-identity=<client-id>
```

**Security Configuration:**

1. Enable managed identity on Azure resource
2. Assign Cosmos DB RBAC role to identity
3. Shell automatically uses identity credentials
4. No secrets needed

**Benefits:**

- Zero credential management
- Automatic token rotation
- Audit trail for all operations
- Complies with security standards

### 3. Account key (development only)

**Best for:** Local development and testing only

**Disadvantages:**

- Keys stored locally (security risk)
- Manual rotation required
- Single point of failure
- Cannot use MFA
- Not recommended for production

**Implementation:**

```bash
cosmosdbshell --connection-string "<connection_string>"
```

**Minimal Risk Usage:**

- Development/testing only
- Never commit to source control
- Use environment variables:

```bash
# Set environment variable
export COSMOS_CONNECTION_STRING="your-connection-string"

# Use in script
cosmosdbshell --connection-string "$COSMOS_CONNECTION_STRING"
```

## Credential management

### Best practices

#### 1. Never hardcode credentials

**❌ Bad:**

```bash
#!/bin/bash
cosmosdbshell --connection-string "DefaultEndpointProtocol=https;AccountName=myaccount;..."
```

**✅ Good:**

```bash
#!/bin/bash
cosmosdbshell --connection-string "$COSMOS_CONNECTION_STRING"
```

#### 2. Use environment variables

**Development:**

```bash
# .env file (development only)
COSMOS_CONNECTION_STRING="your-connection-string"

# Load and use
source .env
cosmosdbshell --connection-string "$COSMOS_CONNECTION_STRING"
```

#### 3. Store in secure vaults

**Azure Key Vault:**

```bash
# Store connection string
az keyvault secret set --vault-name myKeyVault \
  --name cosmos-connection-string \
  --value "your-connection-string"

# Retrieve and use
CONNECTION_STRING=$(az keyvault secret show \
  --vault-name myKeyVault \
  --name cosmos-connection-string \
  --query value -o tsv)

cosmosdbshell --connection-string "$CONNECTION_STRING"
```

**Local Development:**

- Use `.env` files (add to `.gitignore`)
- Load via environment variables
- Never commit secrets

#### 4. Rotate keys regularly

**Key Rotation Process:**

1. Generate new key in Azure portal
2. Update applications with new key
3. Delete old key after verification
4. Test all applications work

## RBAC (role-based access control)

### Implement least privilege

**Principle:** Grant minimum permissions needed

**Recommended Roles:**

| Role | Use Case | Permissions |
| --- | --- | --- |
| `Cosmos DB Account Reader` | Read-only access | View data, metadata |
| `Cosmos DB Built-in Data Reader` | Query operations | Execute queries, read documents |
| `Cosmos DB Built-in Data Contributor` | Full data access | Create, read, update, delete documents |

**Assign Roles:**

```bash
# Get resource ID
RESOURCE_ID=$(az cosmosdb show \
  --resource-group myResourceGroup \
  --name myaccount \
  --query id -o tsv)

# Assign role to user
az role assignment create \
  --role "Cosmos DB Built-in Data Reader" \
  --assignee "<user-principal-id>" \
  --scope "$RESOURCE_ID"
```

### Scope access by container

Create custom roles with limited container access:

```bash
# Custom role for specific container
cat > custom-role.json << 'EOF'
{
  "Name": "Cosmos DB Container Reader",
  "Description": "Read-only access to specific container",
  "Actions": [
    "Microsoft.DocumentDB/databaseAccounts/readonlyKeys/action",
    "Microsoft.DocumentDB/databaseAccounts/read/action"
  ],
  "DataActions": [
    "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/read"
  ],
  "NotDataActions": []
}
EOF
```

## Data protection

### 1. Encryption in transit

**TLS 1.2+ (Default)**

Cosmos DB Shell uses TLS 1.2 or later:

```bash
# Verify TLS version
cosmosdbshell --tls-version 1.2
```

**Configuration:**

```bash
# Force TLS 1.3
cosmosdbshell --min-tls-version 1.3
```

### 2. Encryption at rest

**Enable Encryption at Rest:**

Azure handles encryption automatically, but verify:

1. Go to Azure portal &gt; Cosmos DB Account
2. Settings &gt; Encryption at Rest
3. Verify encryption is enabled

**Verify:**

```bash
# Check encryption settings
az cosmosdb show --resource-group myResourceGroup \
  --name myaccount \
  --query "encryption.keyWrapperProperties" -o table
```

### 3. Customer-managed keys (CMK)

**For Enhanced Security:**

1. Create Azure Key Vault
2. Generate encryption key
3. Configure Cosmos DB to use CMK

**Setup:**

```bash
# Create key vault
az keyvault create --resource-group myResourceGroup \
  --name myKeyVault

# Create key
az keyvault key create --vault-name myKeyVault \
  --name cosmos-key

# Configure Cosmos DB (via Portal or Terraform)
```

## Network security

### 1. IP firewall

**Enable Firewall:**

1. Azure portal &gt; Cosmos DB Account &gt; Firewall
2. Add your IP address(es)
3. Save changes

**Command Line:**

```bash
# Add IP to firewall
az cosmosdb update --resource-group myResourceGroup \
  --name myaccount \
  --ip-range-filter "203.0.113.0/24"
```

### 2. Virtual endpoints

**Restrict to VNet:**

```bash
# Enable virtual endpoint
az cosmosdb update --resource-group myResourceGroup \
  --name myaccount \
  --enable-virtual-network true
```

### 3. Private endpoints

**For Maximum Network Isolation:**

1. Create private endpoint in Azure portal
2. Configure DNS settings
3. Shell connects via private network

**Benefits:**

- No internet exposure
- Restricted network access
- Supports enterprise network isolation policies

## MCP server security

### 1. Local-only binding (default)

**Configuration:**

```json
{
  "cosmosDB.shell.MCP.bindToLocalhost": true
}
```

**Why Important:**

- Prevents remote access
- Only local processes can connect
- Reduces attack surface
- **Recommended:** Keep enabled

### 2. Authentication for MCP

**Microsoft Entra ID authentication:**

```json
{
  "cosmosDB.shell.MCP.enabled": true,
  "cosmosDB.shell.MCP.authMethod": "entra-id"
}
```

### 3. MCP port security

**Secure Configuration:**

```json
{
  "cosmosDB.shell.MCP.enabled": true,
  "cosmosDB.shell.MCP.port": 6128,
  "cosmosDB.shell.MCP.bindToLocalhost": true,
  "cosmosDB.shell.MCP.tlsEnabled": true,
  "cosmosDB.shell.MCP.tlsCertPath": "/path/to/cert.pem"
}
```

### 4. Firewall rules for MCP

**Block External Access:**

```bash
# Windows Firewall
netsh advfirewall firewall add rule name="Block MCP" \
  dir=in action=block protocol=tcp localport=6128

# Linux/macOS (iptables)
sudo iptables -A INPUT ! -i lo -p tcp --dport 6128 -j DROP
```

## Audit and monitoring

### 1. Enable audit logging

**Azure Audit Logs:**

```bash
# View audit logs
az monitor activity-log list \
  --resource-group myResourceGroup \
  --query "[?resourceId=='<cosmos-resource-id>']"
```

### 2. Monitor MCP activity

**Enable MCP Logging:**

```json
{
  "cosmosDB.shell.MCP.logLevel": "info"
}
```

**Review Logs:**

- VS Code Output panel
- Application Insights
- Azure Monitor

### 3. Query metrics

**Monitor Query Performance:**

```bash
# Review query metrics
CS > query "SELECT * FROM c" --show-metrics
```

**Metrics to Track:**

- Request units (RU) used
- Execution time
- Item count

## Compliance and standards

### 1. Data residency

**Ensure Data Stays in Region:**

```bash
# Deploy Cosmos DB in specific region
az cosmosdb create --resource-group myResourceGroup \
  --name myaccount \
  --locations regionName="East US" \
  --databases only
```

### 2. Compliance standards

Azure Cosmos DB maintains a broad set of compliance certifications.

- For the latest certifications and audit reports, see [Microsoft Azure Compliance offerings](https://servicetrust.microsoft.com/DocumentPage/7adf2d9e-d7b5-4e71-bad8-713e6a183cf3).
- For compliance information specific to this service, see [compliance in Azure Cosmos DB](../compliance).

### 3. Data retention

**Set Time-to-Live (TTL) for Sensitive Data:**

```bash
CS > mkcon sensitive_data -pk /id --ttl 2592000
```

This deletes documents after 30 days.

## Security checklist

- [ ] Use Microsoft Entra ID for authentication
- [ ] Enable MFA on Azure account
- [ ] Implement least-privilege RBAC
- [ ] Enable IP firewall
- [ ] Use encrypted connections (TLS 1.2+)
- [ ] Enable audit logging
- [ ] Monitor MCP server activity
- [ ] Store credentials in Key Vault
- [ ] Rotate keys regularly
- [ ] Use private endpoints in production
- [ ] Enable encryption at rest
- [ ] Review compliance requirements
- [ ] Document security policies
- [ ] Train users on security practices

## Common security mistakes

### ❌ Storing keys in code

```bash
# DON'T do this
cosmosdbshell --connection-string "DefaultEndpointProtocol=https;AccountKey=abc123"
```

### ✅ Use environment variables

```bash
# DO this
export COSMOS_CONNECTION_STRING="..."
cosmosdbshell --connection-string "$COSMOS_CONNECTION_STRING"
```

### ❌ Using account key in production

```bash
# DON'T use keys in production with hardcoded connection strings
cosmosdbshell --connect "AccountEndpoint=https://myaccount.documents.azure.com:443/;AccountKey=<your-account-key>;"
```

### ✅ Use managed identity

```bash
# DO use managed identity
cosmosdbshell --connect https://<account-name>.documents.azure.com:443/ --connect-managed-identity=<client-id>
```

### ❌ Leaving MCP open

```json
// DON'T expose MCP publicly
{
  "cosmosDB.shell.MCP.bindToLocalhost": false
}
```

### ✅ Restrict MCP access

```json
// DO restrict to localhost
{
  "cosmosDB.shell.MCP.bindToLocalhost": true
}
```

## Security resources

- [Azure Security Best Practices](/en-us/azure/security/fundamentals/best-practices-and-patterns)
- [Cosmos DB Security](/en-us/azure/cosmos-db/database-security)
- [Key Vault Best Practices](/en-us/azure/key-vault/general/best-practices)
- [RBAC in Cosmos DB](/en-us/azure/cosmos-db/role-based-access-control)

## AI tools

Use these actions to discuss documented security guidance without sharing secrets.

For documentation-only retrieval, use the [Microsoft Learn MCP server](/en-us/training/support/mcp). For a compact guide index, use the [Shell documentation index (`llms.txt`)](llms.txt). The index doesn't change crawler permissions or guarantee retrieval.

Shell MCP requires separate setup and can read or change data under the configured permissions, so review tool calls before approving them. Don't share credentials or sensitive data.

> 
> **[Connect your AI agent](/en-us/azure/cosmos-db/shell/model-context-protocol-setup)** Review authentication and permissions before enabling Shell MCP.
> 
> **[Read as Markdown](/en-us/azure/cosmos-db/shell/security?accept=text/markdown)** Open a text version to copy into your assistant.
> 
> **[Ask ChatGPT](https://chatgpt.com/?hint=search&amp;q=Read%20https%3A%2F%2Flearn.microsoft.com%2Fen-us%2Fazure%2Fcosmos-db%2Fshell%2Fsecurity%20and%20explain%20the%20documented%20Shell%20security%20guidance.%20Use%20sanitized%20configuration%20only.%20Cite%20the%20source%20and%20state%20if%20you%20cannot%20access%20it.)** Explain authentication, access controls, and MCP precautions.
> 
> **[Ask Claude](https://claude.ai/new?q=Read%20https%3A%2F%2Flearn.microsoft.com%2Fen-us%2Fazure%2Fcosmos-db%2Fshell%2Fsecurity%20and%20explain%20the%20documented%20Shell%20security%20guidance.%20Use%20sanitized%20configuration%20only.%20Cite%20the%20source%20and%20state%20if%20you%20cannot%20access%20it.)** Explain authentication, access controls, and MCP precautions.

ChatGPT and Claude receive only the public article URL and a starter prompt. You might need to sign in. If retrieval fails, copy the Markdown text. These links don't configure database access. An assistant's explanation isn't a security assessment of your deployment.

## Support

For security concerns or vulnerability reports:

- [Report Security Issues](https://azure.microsoft.com/support/)
- [Azure Security Advisory](https://msrc.microsoft.com/)