Secure MongoDB Atlas: AuthN and AuthZ / Manage Database User Roles and Privileges

Code Summary: Atlas Database User Authorization

The following provides a summary of the code that creates a custom database role and creates a new user assigned to that role.

Prerequisites

  • Atlas organization ID
  • Atlas Admin API

Usage

Create a custom database role:

The following creates a custom database role named findSalesInsertReturnsRole. The role allows a user to read documents in the sales collection and insert into the returns collection. Update the {groupId} with your credentials.

curl --user "{public key}:{private key}" --digest \
  --header "Accept: application/vnd.atlas.2025-02-19+json" \
  --header "Content-Type: application/json" \
  --include \
  --request POST \
  "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/customDBRoles/roles" \
  --data '{
  "actions": [
    {
      "action": "FIND",
      "resources": [
        {
          "cluster": false,
          "collection": "sales",
          "db": "catalog"
        }
      ]
    },
    {
      "action": "INSERT",
      "resources": [
        {
          "cluster": false,
          "collection": "returns",
          "db": "catalog"
        }
      ]
    }
  ],
  "inheritedRoles": [],
  "roleName": "findSalesInsertReturnsRole"
}'

NOTE: The groupId is the same as projectId.

Create a database user and assign a role:

The following creates a database user and assigns the findSalesInsertReturnsRole role. Update the {groupId} with your credentials.

curl --user "{public key}:{private key}" --digest \
  --header "Accept: application/vnd.atlas.2025-02-19+json" \
  --header "Content-Type: application/json" \
  --include \
  --request POST \
  "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/databaseUsers" \
  --data '{
    "databaseName": "admin",
    "groupId": {groupId},
    "password": "awD1256&78sdES",
    "roles": [
        {
        "databaseName": "admin",
        "roleName": "findSalesInsertReturnsRole"
        }
    ],
    "scopes": [
        {
        "name": "Cluster0",
        "type": "CLUSTER"
        }
    ],
    "username": "Jane"
}'