Docs Menu

Guidance for Atlas Authorization and Authentication

Authentication is the process of verifying the identity of a user. Atlas requires all users to authenticate themselves in order to determine their access.

Although authentication and authorization are closely connected, authentication is distinct from authorization:

  • Authentication verifies the identity of a user.

    Atlas provides robust authentication mechanisms that seamlessly integrate with your existing identity systems, providing secure access to the UI, database, and APIs through strong identity federation. You can manage access to MongoDB Atlas clusters by configuring authentication.

  • Authorization determines the verified user's access to resources and operations.

    Atlas provides Role-Based Access Control (RBAC) to govern access to Atlas. You must grant a user one or more roles that determine the user's access to database resources and operations. Outside of role assignments, the user has no access to the system.

MongoDB Atlas supports a variety of authentication methods to ensure robust security.

  • The best practice for user authentication is utilizing Atlas's seamless integration with identity providers using federated authentication through OpenID Connect (OIDC) or SAML 2.0, and enhancing security with Multi-Factor Authentication (MFA) to ensure a modern authentication and security posture.

  • For workload authentication, Atlas supports OAuth2.0, allowing seamless compatibility with authorization services and integration into your federated IdP.

Atlas requires all users to authenticate to access Atlas UI, Atlas database, and Atlas Administration API. The following authentication methods for each Atlas resource ensure that authentication is both secure and adaptable. Atlas provides the following authentication mechanisms:

We recommend federated authentication for Atlas UI access. To configure federated authentication, you must create Atlas credentials or log in with Google or Github.

For Atlas credentials, we recommend that you use a strong password accompanied by a phishing-resistant MFA, such as biometrics. We highly recommend that you set up a secondary MFA factor to avoid account lock-outs. To ensure MFA access for Atlas credentials, turn on MFA enforcement in the Organization Settings. After you set up federation for your domain, you should use Atlas credentials to authenticate only in the emergency break-glass scenarios when federated authentication is broken.

Federated authentication allows you to manage all authentication to the Atlas UI across multiple systems and applications through a central identity provider. For UI access, Atlas supports workforce identity federation using SAML 2.0. You can use any SAML compatible identity provider such as Okta, Microsoft Entra ID, or Ping Identity to enforce security policies such as password complexity, credential rotation, and MFA within your identity provider.

You must configure the IP access list in the Atlas UI to allow only connections from IP ranges that include your users and application servers.

To learn more, see Configure Federated Authentication.

For any human user that has access to the Atlas control plane, we recommend that you require MFA for enhanced security. When MFA is enabled, Atlas requires two forms of identification:

  • The user's credentials

  • One of the following recommended factors:

    • Security keys

    • Biometrics

    • OTP authenticators

    • Push notifications

    • SMS (not recommended as primary factor)

    • Email (not recommended as primary factor)

To learn more, see Manage Your Multi-Factor Authentication Options.

Atlas supports various database authentication mechanisms.

To configure workforce (human user) access to your Atlas database via tools such as MongoDB Shell and Compass, use Workforce Identity Federation with OIDC.

To configure workload (application) access to your Atlas database using MongoDB drivers, use Workload Identity Federation, AWS-IAM authentication, or X.509 certificate authentication. We recommend SCRAM password authentication for use only in development or testing environments.

Atlas also supports:

Workforce Identity Federation allows you to manage all authentication to the Atlas database through your identity provider. For database access, we recommend OIDC-compatible identity providers such as Okta, Microsoft Entra ID, or Ping Identity to enforce security policies such as password complexity, credential rotation, and MFA within your identity provider.

To learn more, see Set up Workforce Identity Federation with OIDC.

Workload Identity Federation enables applications running in cloud environments like Azure and Google Cloud to authenticate with Atlas without the need to manage separate database user credentials. With Workload Identity Federation, you can manage Atlas database users using Azure Managed Identities, Google Service Accounts, or any OAuth 2.0-compliant service. These authentication mechanisms simplify management and enhance security by allowing for passwordless access to the Atlas database.

We recommend Workload Identity Federation for all applications running in production. You shouldn't allow human users to connect except in the most extreme break-glass emergency scenarios.

You can also authenticate through AWS IAM roles.

To learn more, see the following:

We recommend that you use Workforce or Workload Identity Federation through an identity provider for security and ease of access to all aspects of the Atlas control and data plane.

If you don't have an identity provider for federation, Atlas clusters also support X.509 client certificates for user authentication. X.509 certificates provide the security of mutual TLS, making them suitable for staging and production environments, and you can bring your own certificate authority for use with X.509. The disadvantage of X.509 is that you must manage certificates and the security of these certificates on the application side, while Workload Identity Federation allows for passwordless access and easier application security.

Atlas clusters also support SCRAM password authentication for user authentication, but we recommend SCRAM only for use in development and test environments.

If you leverage X.509 or SCRAM authentication, we recommend that you use third-party secrets manager like HashiCorp Vault or AWS Secrets Manager to generate and store complex database credentials.

To learn more, see the following manual pages:

Atlas also supports creating temporary database users that automatically expire after the predefined times. A user can be created for the following periods:

  • 6 hours

  • 1 day

  • 1 week

To learn more, see Configure Database Users.

We recommend using a third-party secrets manager like HashiCorp Vault or AWS Secrets Manager to generate and store complex database credentials. A secrets manager can generate database credentials dynamically based on configured roles for Atlas databases.

To learn more, see the blog Manage MongoDB Atlas Database Secrets in HashiCorp Vault.

Atlas provides two ways to authenticate to the Atlas Administration API:

Service accounts use industry-standard OAuth2.0 to securely authenticate with Atlas through the Atlas Administration API. We recommend that you use service accounts instead of API keys when possible because they provide added security through use short-lived access tokens and required credential rotations.

Service accounts are available as a Preview feature, and you can manage programmatic access for service accounts only by using the Atlas UI or the Atlas Administration API. You can't manage programmatic access for service accounts through the Atlas CLI or Terraform.

To learn more, see Service Accounts Overview.

If you don't use service accounts, you can use API key-based authentication to securely manage programmatic access. API key-based authentication uses HTTP Digest authentication to protect requests. The API public key functions as the username, and the corresponding private key serves as the password. You should store these keys in a third party secrets management system, such as AWS Secrets Manager or HashiCorp Vault. To learn how to securely store these keys in Vault, see the blog Manage MongoDB Atlas Database Secrets in HashiCorp Vault.

To further enhance security and minimize the risk of unauthorized access:

To learn more, see Atlas Administration API Authentication.

To learn our recommendations for deployments, which relate to authentication, see Guidance for Atlas Orgs, Projects, and Clusters.

You must implement Atlas's robust Role-Based Access Control (RBAC) to effectively manage access across all resources. Atlas includes built-in roles that provide different levels of access commonly needed for managing the Atlas control plane. For connecting to Atlas clusters in the data plane, we recommend using database fine-grained custom roles to provide granular scoping based on the access to the data access required for the role to perform its function. This approach enables you to follow the principle of least privilege.

Additionally, by integrating Atlas with a federated identity provider, you can use just-in-time provisioning by mapping identity provider groups to Atlas roles. This streamlines access management and ensures secure and organized role assignments throughout the platform. You can grant access programmatically based on the provisioning process of your orchestration layer.

In general, it is a best practice to always restrict access to upper environments to only programmatic service accounts with scripts that are tested for security and deterministic outcomes. Human access should only be allowed in lower environments during development and testing.

You can assign users, service accounts, and API keys to predefined roles, specifying the actions they can perform within Atlas organizations, projects, or both. Use Identity Federation to manage access by linking your identity provider groups to Atlas roles through group-role mappings.

We recommend that you use a modern federated Identity Provider (IdP) that provides SSO with SAML such as Azure Entra ID, Okta, or Ping Identity as this makes the authorization process more secure and supports the flexibility needed to programmatically assign IdP groups to Atlas roles. You should restrict your company's domain from preventing users from logging into Atlas when they are not authorized for access, which you can do by following the procedure in Manage Domain Mapping for Federated Authentication. From here, we recommend that you map your IdP groups to Atlas roles as shown in Role Mapping Process.

If you have followed the standard Atlas hierarchy of a single billing organization with a linked organization for each BU or department, then you should restrict organization users to the operations or platform team admins. In contrast, you should assign project roles to the development or product teams responsible for building applications. Only programmatic access should be allowed in upper environments. The following recommendations for the most commonly used roles can serve as a general guideline:

  • The Organization Owner role should be heavily restricted and not assigned to a human, as it has the ability to change organization-wide settings and delete configurations. This role should be assigned to a service account which you use only to initially set up and configure the organization. Minimize configuration changes after the initial creation. To avoid account lockouts, you can create the following items:

    • SAML Organization Owner group with Just-in-Time Access.

    • API key with the Organization Owner role. Keep it in a secure place with strong access management for break-glass emergency scenarios.

  • The Organization Member role should be for admins on the operations and platform team that can view settings and configuration for the organization.

  • The Organization Project Creator role should be a programmatic service account used to create projects on behalf of new applications for development and product teams.

  • The Organization Billing Admin role should be a programmatic service account used to pull invoices programmatically from the Billing API and feed them into your FinOps tool. This same service account should have access to all linked organizations for which it is responsible for reporting usage.

  • The Project Owner role should be used for governance enforced by the operations and provisioning team. Assign this role to a programmatic service account, as it has the ability to create and delete clusters. For sandbox environments, you may consider granting a user Project Owner access to enable them to quickly provision clusters for testing code and use cases without going through the orchestration deployment pipeline.

  • In lower environments, use the Project Data Access Admin role to grant access to the development team building the application so they can access the query and performance metrics of the cluster during development and testing. This access allows them to debug data issues with the Data Explorer. Don't allow this role in production environments. It has the ability to view and edit data, including creating and dropping databases, collections, and indexes on the cluster, which is useful for rapid experimentation and development. If you are not comfortable giving development teams this level of access in the development environment, you can grant them read-only access to the cluster's data and performance statistics with the Project Data Access Read Only role.

    To grant read-only access to the cluster's data in production environments, use the Project Observability Viewer role.

To learn more, see Atlas User Roles.

Workforce and workload users can be assigned fine-grained database roles, predefined or custom, with permissions tailored to specific projects or individual clusters. In staging and production environments, we recommend using Identity Federation to streamline access management by linking your Identity Provider (IdP) to Atlas for a more modern and streamlined authentication and authorization flow for data access.

By configuring Group Membership in your IdP, you can map groups to database users, simplifying access control within the IdP. However, for workload identities, we recommend assigning roles directly using the users claim instead of groups. In development and test environments, you can default to the predefined readWriteAny role to simplify the development and testing process. When moving the application to higher environments, you should build a custom role to restrict the access that the application server has based on the principle of least privilege.

To learn more, see the following:

See Terraform examples to enforce our Staging/Prod recommendations across all pillars in one place in Github.

The following examples configure authentication and custom roles using Atlas tools for automation.

Run the following command to create a user authentication with IAM credentials to a specified cluster.

atlas dbusers create \
--projectId "6698000acf48197e089e4085" \
--username "MyRoleARN" \
--awsIAMType "ROLE" \
--role "clusterMonitor" \
--scope "myCluster"

Run the following command to create a temporary user with SCRAM authentication.

atlas dbusers create \
--projectId 6698000acf48197e089e4085 \
--username "tempUser" \
--password "securePassword" \
--role "readWrite" \
--scope "myCluster" \
--deleteAfter "2025-02-01T12:00:00Z"

Run the following command to configure Workforce Identity Federation with OIDC.

atlas federatedAuthentication federationSettings identityProvider create oidc Azure \
--audience "https://management.azure.com/" \
--authorizationType "USER" \
--desc "oidc-for-azure" \
--federationSettingsId "5d1113b25a115342acc2d1aa" \
--groupsClaim "groups" \
--idpType "WORKFORCE" \
--issuerUri "https://sts.windows.net/" \
--userClaim "sub"

The following examples demonstrate how to configure authentication and authorization. Before you can create resources with Terraform, you must:

  • Create your paying organization and create an API key for the paying organization. Store your API key as environment variables by running the following command in the terminal:

    export MONGODB_ATLAS_PUBLIC_KEY="<insert your public key here>"
    export MONGODB_ATLAS_PRIVATE_KEY="<insert your private key here>"
  • Install Terraform

You must create the following files for each example. Place the files for each example in their own directory. Change the IDs and names to use your values. Then run the commands to initialize Terraform, view the Terraform plan, and apply the changes.

locals {
tags = {
CreatedBy = "Terraform"
Owner = var.owner
Module = "tf-example-oidc-azure"
Name = var.project_name
}
}
resource "azurerm_resource_group" "this" {
name = var.project_name
location = var.location
tags = local.tags
}
resource "azurerm_virtual_network" "this" {
name = var.project_name
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.this.location
resource_group_name = azurerm_resource_group.this.name
tags = local.tags
}
resource "azurerm_subnet" "internal" {
name = "internal"
resource_group_name = azurerm_resource_group.this.name
virtual_network_name = azurerm_virtual_network.this.name
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_public_ip" "vm-public-ip" {
name = "public-ip-${var.project_name}"
location = var.location
resource_group_name = azurerm_resource_group.this.name
allocation_method = "Dynamic"
domain_name_label = var.project_name
tags = local.tags
}
resource "azurerm_network_interface" "this" {
name = "ip-${var.project_name}"
location = var.location
resource_group_name = azurerm_resource_group.this.name
tags = local.tags
ip_configuration {
subnet_id = azurerm_subnet.internal.id
name = "public"
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.vm-public-ip.id
}
}
resource "azurerm_user_assigned_identity" "this" {
location = var.location
name = var.project_name
resource_group_name = azurerm_resource_group.this.name
tags = local.tags
}
resource "azurerm_linux_virtual_machine" "this" {
name = var.project_name
resource_group_name = azurerm_resource_group.this.name
location = var.location
size = "Standard_F2"
admin_username = var.vm_admin_username
custom_data = data.cloudinit_config.this.rendered
network_interface_ids = [azurerm_network_interface.this.id]
tags = local.tags
admin_ssh_key {
username = var.vm_admin_username
public_key = var.ssh_public_key
}
source_image_reference {
publisher = "Canonical"
offer = "0001-com-ubuntu-server-jammy"
sku = "22_04-lts"
version = "latest"
}
os_disk {
storage_account_type = "Standard_LRS"
caching = "ReadWrite"
disk_size_gb = 30
}
identity {
type = "UserAssigned"
identity_ids = [azurerm_user_assigned_identity.this.id]
}
}
variable "user" {
description = "MongoDB Atlas User"
type = list(string)
default = ["dbuser1", "dbuser2"]
}
variable "database_name" {
description = "The Database in the cluster"
type = list(string)
}
variable "org_id" {
description = "MongoDB Organization ID"
type = string
}
variable "project_id" {
description = "MongoDB Atlas Project ID"
type = string
}
variable "connection_strings" {
description = "List of MongoDB connection strings to the cluster"
type = list(string)
}
variable "token_audience" {
description = "The token audience used by the OIDC identity provider"
type = string
default = "https://management.azure.com/" # Example audience
}
variable "trusted_domains" {
description = "List of associated domains to trust"
type = list(string)
default = ["myOrg.com", "another-trusted-domain.org"] # Example domains
}
org_id = "32b6e34b3d91647abb20e7b8"
project_id = "67212db237c5766221eb6ad9"
user = ["testUser"]
database_name = ["myTestDb"]
connection_strings = ["mongodb+srv://cluster0.mongodb.net"]
token_audience = "https://management.azure.com/"
trusted_domains = ["myOrg.com", "example-domain.org"]

Use the following to create an Atlas user with username and password authentication.

locals {
test_user_password = random_password.password.result
}
# Generates 12 characters long random password without special characters
resource "random_password" "password" {
length = 12
special = false
}
resource "mongodbatlas_database_user" "user1" {
username = var.user[0]
password = local.test_user_password
project_id = var.project_id
auth_database_name = "admin"
scopes = var.clusters[0]
roles {
role_name = "readWriteAny"
database_name = var.database_name[0]
}
}
output "user1" { value = mongodbatlas_database_user.user1.username }
output "userpwd" { value = mongodbatlas_database_user.user1.password sensitive = true }

Use the following example to set up an OIDC federated identity provider in Atlas, for using it with Azure and then create an OIDC federated authentication user. It uses OIDC tokens issued by Azure Active Directory to allow access.

# Connection string to use in this configuration
locals {
mongodb_uri = var.connection_strings[0]
}
# Fetch MongoDB Atlas Federated Settings
data "mongodbatlas_federated_settings" "this" {
org_id = var.org_id
}
# Configure an identity provider for federated authentication
resource "mongodbatlas_federated_settings_identity_provider" "oidc" {
federation_settings_id = data.mongodbatlas_federated_settings.this.id
associated_domains = var.trusted_domains
audience = var.token_audience
authorization_type = "USER"
description = "OIDC Identity Provider for Azure AD"
# Replace with actual Azure Tenant ID
issuer_uri = "https://sts.windows.net/${data.azurerm_client_config.current.tenant_id}/"
idp_type = "WORKFORCE"
name = "OIDC-for-azure"
protocol = "OIDC"
user_claim = "sub" # Claim to extract the user's principal identity
}
resource "mongodbatlas_federated_settings_org_config" "this" {
federation_settings_id = data.mongodbatlas_federated_settings.this.id
org_id = var.org_id
domain_restriction_enabled = false
domain_allow_list = []
data_access_identity_provider_ids = [mongodbatlas_federated_settings_identity_provider.oidc.idp_id]
}
# Create an OIDC-authenticated Database User
resource "mongodbatlas_database_user" "oidc" {
project_id = var.project_id
username = "${mongodbatlas_federated_settings_identity_provider.oidc.idp_id}/${data.azurerm_client_config.current.client_id}"
oidc_auth_type = "USER"
auth_database_name = "$external" # Required when using OIDC for USER authentication
roles {
role_name = "atlasAdmin"
database_name = "admin"
}
}
# Azure-specific data source needed for Tenant ID and Client ID
data "azurerm_client_config" "current" {}
output "vm_fqdn" {
value = azurerm_public_ip.vm-public-ip.fqdn
description = "Fully Qualified Domain Name (FQDN) of the Virtual Machine (VM)"
}
output "ssh_connection_string" {
value = "ssh ${var.vm_admin_username}@${azurerm_public_ip.vm-public-ip.fqdn}"
description = "Useful for connecting to the instance"
}
output "user_test_conn_string" {
value = "mongodb+srv://${var.user[0]}:<password>@${replace(local.mongodb_uri, "mongodb+srv://", "")}/?retryWrites=true"
description = "Connection string for testing regular database user access"
sensitive = true
}
output "user_oidc_conn_string" {
value = "mongodb+srv://${mongodbatlas_database_user.oidc.username}:<OIDCToken>@${replace(local.mongodb_uri, "mongodb+srv://", "")}/?authMechanism=MONGODB-OIDC&retryWrites=true"
description = "Connection string for OIDC-authenticated user"
sensitive = true
}

Use the following to grant users admin rights on the cluster and project member rights for the projects in the cluster.

resource "mongodbatlas_database_user" "admin_user" {
project_id = "6698000acf48197e089e4085"
username = "adminUser"
password = "securePassword" # Use a secure password
auth_database_name = "admin"
roles {
role_name = "atlasAdmin" # Admin role for the cluster
database_name = "admin"
}
roles {
role_name = "readWriteAnyDatabase" # Project member rights
database_name = "admin"
}
}

Run the following command to create a database user from a specific group in the Identity Provider. You can manage the user authentication and authorization through the identity provider, Okta. The command also grants the users in the identity provider group dbAdmin and readWrite privileges on the Atlas cluster.

atlas dbusers create \
--projectId "6698000acf48197e089e4085" \
--username "okta/my-idp-group" \
--role "readWrite,dbAdmin" \
--oidcType "IDP_GROUP"

Run the following command to create an OIDC-compatible identity providers from your federation settings.

atlas federatedAuthentication federationSettings identityProvider create oidc IDPName \
--audience "api://12345678-1234-1234-1234-123456789abc" \
--authorizationType "GROUP" \
--clientId "abcdef12-3456-7890-abcd-ef1234567890" \
--desc "MyOIDCProvider test" \
--federationSettingsId "5d1113b25a115342acc2d1aa" \
--groupsClaim "groups" \
--idpType "WORKLOAD" \
--issuerUri "https://sts.windows.net/12345678-1234-1234-1234-123456789abc/" \
--userClaim "sub" \
--associatedDomain "example.com"

The following examples demonstrate how to configure authentication and authorization. Before you can create resources with Terraform, you must:

  • Create your paying organization and create an API key for the paying organization. Store your API key as environment variables by running the following command in the terminal:

    export MONGODB_ATLAS_PUBLIC_KEY="<insert your public key here>"
    export MONGODB_ATLAS_PRIVATE_KEY="<insert your private key here>"
  • Install Terraform

You must create the following files for each example. Place the files for each example in their own directory. Change the IDs and names to use your values. Then run the commands to initialize Terraform, view the Terraform plan, and apply the changes.

locals {
tags = {
CreatedBy = "Terraform"
Owner = var.owner
Module = "tf-example-oidc-azure"
Name = var.project_name
}
}
resource "azurerm_resource_group" "this" {
name = var.project_name
location = var.location
tags = local.tags
}
resource "azurerm_virtual_network" "this" {
name = var.project_name
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.this.location
resource_group_name = azurerm_resource_group.this.name
tags = local.tags
}
resource "azurerm_subnet" "internal" {
name = "internal"
resource_group_name = azurerm_resource_group.this.name
virtual_network_name = azurerm_virtual_network.this.name
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_public_ip" "vm-public-ip" {
name = "public-ip-${var.project_name}"
location = var.location
resource_group_name = azurerm_resource_group.this.name
allocation_method = "Dynamic"
domain_name_label = var.project_name
tags = local.tags
}
resource "azurerm_network_interface" "this" {
name = "ip-${var.project_name}"
location = var.location
resource_group_name = azurerm_resource_group.this.name
tags = local.tags
ip_configuration {
subnet_id = azurerm_subnet.internal.id
name = "public"
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.vm-public-ip.id
}
}
resource "azurerm_user_assigned_identity" "this" {
location = var.location
name = var.project_name
resource_group_name = azurerm_resource_group.this.name
tags = local.tags
}
resource "azurerm_linux_virtual_machine" "this" {
name = var.project_name
resource_group_name = azurerm_resource_group.this.name
location = var.location
size = "Standard_F2"
admin_username = var.vm_admin_username
custom_data = data.cloudinit_config.this.rendered
network_interface_ids = [azurerm_network_interface.this.id]
tags = local.tags
admin_ssh_key {
username = var.vm_admin_username
public_key = var.ssh_public_key
}
source_image_reference {
publisher = "Canonical"
offer = "0001-com-ubuntu-server-jammy"
sku = "22_04-lts"
version = "latest"
}
os_disk {
storage_account_type = "Standard_LRS"
caching = "ReadWrite"
disk_size_gb = 30
}
identity {
type = "UserAssigned"
identity_ids = [azurerm_user_assigned_identity.this.id]
}
}
# Azure Variables
variable "token_audience" {
type = string
default = "https://management.azure.com/"
description = "Used as resource when getting the access token. See more in the [Azure documentation](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http)"
}
# MongoDB Atlas variables
variable "org_id" {
type = string
description = "MongoDB Atlas Organization ID"
}
variable "project_id" {
type = string
description = "MongoDB Atlas Project ID"
}
variable "project_name" {
type = string
description = "MongoDB Atlas Project Name"
}
variable "connection_strings" {
type = list(string)
description = "MongoDB Atlas Cluster Standard Connection Strings"
}
org_id = "32b6e34b3d91647abb20e7b8"
project_id = "67212db237c5766221eb6ad9"
project_name = "My Project"
connection_strings =
token_audience = "https://management.azure.com/"
output "vm_fqdn" {
value = azurerm_public_ip.vm-public-ip.fqdn
description = "Fully Qualified Domain Name (FQDN) of the Virtual Machine (VM)"
}
output "ssh_connection_string" {
value = "ssh ${var.vm_admin_username}@${azurerm_public_ip.vm-public-ip.fqdn}"
description = "Useful for connecting to the instance"
}
output "user_test_conn_string" {
value = "mongodb+srv://${local.test_user_username}:${local.test_user_password}@${replace(mongodbatlas_advanced_cluster.this.connection_strings[0].standard_srv, "mongodb+srv://", "")}/?retryWrites=true"
sensitive = true
description = "Useful for connecting to the database from Compass or other tool to validate data"
}
output "user_oidc_conn_string" {
value = local.mongodb_oidc_uri
sensitive = true
description = "Useful to see the format of the OIDC connection string"
}

Use the following to set up an OIDC federated identity provider in Atlas, for using it with Azure. It allows access by using OIDC tokens issued by Azure Active Directory.

# Connection string to use in this configuration
locals {
mongodb_uri = var.connection_strings[0]
}
# Atlas organization details to use in the configuration
data "mongodbatlas_federated_settings" "this" {
org_id = var.org_id
name = var.project_name
project_id = var.project_id
}
# Configure an identity provider for federated authentication
resource "mongodbatlas_federated_settings_identity_provider" "oidc" {
federation_settings_id = data.mongodbatlas_federated_settings.this.id
audience = var.token_audience
authorization_type = "USER"
description = "oidc-for-azure"
# e.g. "https://sts.windows.net/91405384-d71e-47f5-92dd-759e272cdc1c/"
issuer_uri = "https://sts.windows.net/${azurerm_user_assigned_identity.this.tenant_id}/"
idp_type = "WORKLOAD"
name = "OIDC-for-azure"
protocol = "OIDC"
# groups_claim = null
user_claim = "sub"
}
resource "mongodbatlas_federated_settings_org_config" "this" {
federation_settings_id = data.mongodbatlas_federated_settings.this.id
org_id = var.org_id
domain_restriction_enabled = false
domain_allow_list = []
data_access_identity_provider_ids = [mongodbatlas_federated_settings_identity_provider.oidc.idp_id]
}

Use the following to create an OIDC federated authentication user.

resource "mongodbatlas_database_user" "oidc" {
project_id = var.project_id
username = "${mongodbatlas_federated_settings_identity_provider.oidc.idp_id}/${azurerm_user_assigned_identity.this.principal_id}"
oidc_auth_type = "USER"
auth_database_name = "$external" # required when using OIDC USER authentication
roles {
role_name = "atlasAdmin"
database_name = "admin"
}
}

Use the following to create a custom role named my_custom_role which allows update, add, and delete operations on any collection in the database named myDb.

resource "mongodbatlas_custom_db_role" "create_role" {
project_id = var.project_id
role_name = "my_custom_role"
actions {
action = "UPDATE"
resources {
database_name = "myDb"
}
}
actions {
action = "INSERT"
resources {
database_name = "myDb"
}
}
actions {
action = "REMOVE"
resources {
database_name = "myDb"
}
}
}

For an example of an Atlas project with the Atlas role assigned to a specific group, see Examples.