July 19th, 2022

Role-based access control in Azure Cosmos DB API for MongoDB: Now in preview

Richa Gaur
Program Manager

Role based access control (RBAC) is a much-needed capability in any database for enterprises. It lets you simplify your access control mechanism without added management. We have introduced RBAC in Azure Cosmos DB API for MongoDB, which allows you to:

  1. Authorize your data requests with a fine-grained, role-based permission model
  2. Audit your diagnostic logs to retrieve the user identity for each database operation

How does it work?

API for MongoDB RBAC is built on concepts that are commonly found in other RBAC systems like Azure RBAC, including:

  • Role definition is a set of actions that one can perform using a given role. These actions map to database operations like read, write, etc. There are built-in roles like “read” and you can create custom roles as well
  • User is the identity represented by a username and password
  • The user is then mapped to a role through role assignment, this user can perform every action defined in the role definition of the mapped role

Image rbac mongo

How to get started?

Using RBAC is a simple 4 step process.

1. Enable RBAC on Azure Cosmos DB API for MongoDB

To use RBAC in API for MongoDB, you need to enable this capability in your Azure Cosmos DB account.

Azure CLI

az cloud set -n AzureCloud
az login
az account set --subscription <your subscription ID>

az cosmosdb update -n <account_name> -g <azure_resource_group> --capabilities EnableMongoRoleBasedAccessControl
2. Create user definition

Create user definition with built-in read role definition. There are other built-in roles defined by the system, you can check them out here.

Azure CLI

#!/bin/bash

account_name=<YOUR_DB_ACCOUNT>
rg=<YOUR_RG>
db=<YOUR_DB_NAME>
username=<YOUR_USERNAME>
password=<YOUR_PASSWORD>

printf '{
    "Id": "'"$db.$username"'",
    "UserName": "'"$username"'",
    "Password": "'"$password"'",
    "DatabaseName": "'"$db"'",
    "CustomData": "some_random_info",
    "Mechanisms": "SCRAM-SHA-256",
    "Roles": [{
        "Role": "read",
        "Db": "'"$db"'"
    }]
 }'>create_user.json

az cosmosdb mongodb user definition create --account-name $account_name --resource-group $rg --body @create_user.json
3. Test RBAC

You are now ready to use your account using RBAC. Authenticate the client using the username and password provided in creating the user.

Python

from pymongo import MongoClient

client = MongoClient("mongodb://<USERNAME>:<PASSWORD>@<YOUR_HOSTNAME>:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000", username="<YOUR_USER>", password="<YOUR_PASSWORD>", authSource='<YOUR_DATABASE>', authMechanism='SCRAM-SHA-256', appName="<YOUR appName FROM CONNECTION STRING IN AZURE PORTAL>")

db = client[“<your_database_name>”]
col = db[“<your_collection_name>”]

for doc in col.find({}):
   print(doc)
4. Audit your requests

Users can audit the operation performed on the database by enabling diagnostics logging. See, Monitor Azure Cosmos DB data by using Azure Diagnostic settings | Microsoft Docs

Select MongoRequests table in the diagnostics logs settings, this table contains UserId column against each request. This column would be blank for accounts not using RBAC.

Image diagnostics

Use below query to find out the users performing the requests.

KQL (Kusto Query Language)

CDBMongoRequests
| where OperationName == "Find"
| project DatabaseName, CollectionName, UserId, TimeGenerated

 

Next steps

Create custom role definitions

You can create a new role definition if you need to define custom set of permissions. Checkout full list of Azure CLI commands here.

Azure CLI

#!/bin/bash

account_name=<YOUR_DB_ACCOUNT>
rg=<YOUR_RG>
db=<YOUR_DB_NAME>
role_name=<YOUR_ROLE_NAME>
collection_name=<COLLECTION_NAME>

printf '{
    "Id": "'"$db.$role_name"'",
    "RoleName": "'"$role_name"'",
    "Type": "CustomRole",
    "DatabaseName": "'"$db"'",
    "CustomData": "some_random_info",
    "Privileges":[
        {
            "Resource":{
                "Db":  "'"$db"'",
                "Collection": "'"$collection_name"'"
            },
            "Actions": [
                    "insert",
                    "find"
                ]
        }
    ],
    "Roles":[]
 }'>create_role.json

az cosmosdb mongodb role definition create --account-name $account_name --resource-group $rg --body @create_role.json
Enforcing RBAC as the only authentication method

Disable any other auth mechanism for Azure Cosmos DB by updating the ARM template. Add the following property in your existing template or create a new one.

JSON

"resources": [
    {
        "type": " Microsoft.DocumentDB/databaseAccounts",
        "properties": {
            "disableLocalAuth": true,
        },
    },
 ]

 

Learn more

The granularity of this permission model lets you control very precisely what a client is allowed to do. Moreover, you can always come back to audit logs and identify what operation was issued by which user in case of any dilemma.

Author

Richa Gaur
Program Manager

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Harley Jácome

    Enforcing RBAC as the only authentication method does not work for MongoDB.

    Thank you, excellent post. But the last part is not working.

    After trying to follow the section for disabling localAuth, I get this error:

    Status Message: DisableLocalAuth is only allowed to be configured for SQL API account. ActivityId: 622fb39b-456d-4679-b446-d3f2df1026cd, Microsoft.Azure.Documents.Common/2.14.0 (Code:BadRequest) CorrelationId: 0c4e5847-1d3c-4621-b10d-5e01c9b57e67

    I tried re-deploying the database using ARM or by running the command:

    az resource update --ids $cosmosdb.id --set properties.disableLocalAuth=true --latest-include-preview

    It is an issue because...

    Read more