Navigation

Configure MongoDB with Kerberos Authentication and Active Directory Authorization

New in version 3.4: MongoDB Enterprise supports querying an LDAP server for the LDAP groups to which an authenticated user belongs. MongoDB maps the LDAP distinguished names (DN) of each returned group to roles on the admin database. MongoDB authorizes the user based on the mapped roles and their associated privileges. See LDAP Authorization for more information.

MongoDB Enterprise supports authentication using a Kerberos service. Kerberos is an industry standard authentication protocol for large client/server systems.

This tutorial describes how to configuring MongoDB to perform authentication through a Kerberos server and authorization through an Active Directory (AD) server via the platform libraries.

Prerequisites

Important

Thoroughly familiarize yourself with the following subjects before proceeding:

A full description of AD is beyond the scope of this tutorial. This tutorial assumes prior knowledge of AD.

MongoDB supports using SASL mechanisms for binding between the MongoDB server and AD. A full description of SASL, SASL mechanisms, or the specific AD configuration requirements for a given SASL mechanism are beyond the scope of this tutorial. This tutorial assumes prior knowledge of SASL and its related subject matter.

Setting up and configuring a Kerberos deployment is beyond the scope of this document. This tutorial assumes you have configured a Kerberos service principal for each mongod and mongos instance in your MongoDB deployment, and you have a valid keytab file for for each mongod and mongos instance.

For replica sets and sharded clusters, ensure that your configuration uses fully qualified domain names (FQDN) rather than IP addresses or unqualified hostnames. You must use the FQDN for GSSAPI to correctly resolve the Kerberos realms and allow you to connect.

To verify that you are using MongoDB Enterprise, pass the --version command line option to the mongod or mongos:

mongod --version

In the output from this command, look for the string modules: subscription or modules: enterprise to confirm you are using the MongoDB Enterprise binaries.

Considerations

This tutorial explains configuring MongoDB for Kerberos authentication and AD authorization.

To perform this procedure on your own MongoDB server, you must modify the given procedures with respect to your own specific infrastructure, especially Kerberos configurations, constructing AD queries, or managing users.

Transport Layer Security

By default, MongoDB creates a TLS/SSL connection when binding to the AD server. This requires configuring the host of the MongoDB server to have access to the AD server’s Certificate Authority (CA) certificates.

This tutorial provides instructions for the required host configurations.

This tutorial assumes you have access to the AD server’s CA certificates and can create a copy of the certificates on the MongoDB server.

Example Active Directory Schema

This tutorial uses the following example AD objects as the basis for the provided queries, configurations, and output. Each object shows only a subset of the possible attributes.

User Objects

dn:CN=bob,CN=Users,DC=marketing,DC=example,DC=com
userPrincipalName: [email protected]
memberOf: CN=marketing,CN=Users,DC=example,DC=com

dn:CN=alice,CN=Users,DC=engineering,DC=example,DC=com
userPrincipalName: [email protected]
memberOf: CN=web,CN=Users,DC=example,DC=com
memberOf: CN=PrimaryApplication,CN=Users,DC=example,DC=com

dn:CN=sam,CN=Users,DC=dba,DC=example,DC=com
userPrincipalName: [email protected]
memberOf: CN=dba,CN=Users,DC=example,DC=com
memberOf: CN=PrimaryApplication,CN=Users,DC=example,DC=com

dn:CN=joe,CN=Users,DC=analytics,DC=example,DC=com
userPrincipalName: [email protected]
memberof: CN=marketing,CN=Users,DC=example,DC=com

Group Objects

dn:CN=marketing,CN=Users,DC=example,DC=com
member:CN=bob,CN=Users,DC=marketing,DC=example,DC=com
member:CN=joe,CN=Users,DC=analytics,DC=example,DC=com

dn:CN=engineering,CN=Users,DC=example,DC=com
member:CN=web,CN=Users,DC=example,DC=com
member:CN=dba,CN=users,DC=example,DC=com

dn:CN=web,CN=Users,DC=example,DC=com
member:CN=alice,CN=Users,DC=engineering,DC=example,DC=com

dn:CN=dba,CN=Users,DC=example,DC=com
member:CN=sam,CN=Users,DC=dba,DC=example,DC=com

dn:CN=PrimaryApplication,CN=Users,DC=example,DC=com
member:CN=sam,CN=Users,DC=dba,DC=example,DC=com
member:CN=alice,CN=Users,DC=engineering,DC=example,DC=com

Active Directory Credentials

This tutorial uses a username and password for performing queries on the AD server. The credentials provided must have sufficient privileges on the AD server for supporting queries related to security.ldap.userToDNMapping or security.ldap.authz.queryTemplate.

Replica Sets

MongoDB LDAP authorization requires every mongod in the replica set to be on at least MongoDB 3.4.0 or later.

Sharded Clusters

MongoDB LDAP authorization requires every mongod and mongos in the sharded cluster to be on at least MongoDB 3.4.0 or later.

Procedure

1

Configure TLS/SSL for the server running MongoDB.

To connect to the AD (AD) server via TLS/SSL, the mongod or mongos require access to the AD server’s Certificate Authority (CA) certificate.

On Linux, specify the AD server’s CA certificates via the TLS_CACERT or TLS_CACERTDIR option in the ldap.conf file.

Your platform’s package manager creates the ldap.conf file while installing MongoDB Enterprise’s libldap dependency. For complete documentation on the configuration file or the referenced options, see ldap.conf.

On Microsoft Windows, load the AD server’s Certificate Authority (CA) certificates with the platform’s credential management tool. The exact credential management tool is Windows version dependent. To use the tool, refer to its documentation for your version of Windows.

If mongod or mongos cannot access to the AD CA files, they cannot create TLS/SSL connections to the Active Directory server.

Optionally, set security.ldap.transportSecurity to none to disable TLS/SSL.

Warning

Setting transportSecurity to none transmits plaintext information, including user credentials, between MongoDB and the AD server.

2

(Windows only) Assign Service Principal Name to MongoDB Windows Service.

For MongoDB servers running on the Windows operating system, you must use setspn.exe to assign the service principal name (SPN) to the account running the MongoDB service.

setspn.exe -S <service>/<fully qualified domain name> <service account name>

Example

For example, if a mongod runs as a service named mongodb on mongodbserver.example.com with the service account name mongodb_dev@example.com, the command to assign the SPN would look as follows:

setspn.exe -S mongodb/mongodbserver.example.com mongodb_dev@example.com

Note

Windows Server 2003 does not support setspn.exe -S. For complete documentation on setspn.exe, see setspn.exe.

2

(Linux only) Create keytab file for the MongoDB server.

For MongoDB servers running on the Linux platform, you must ensure the server has a copy of the keytab file specific to the MongoDB instance running on that server.

You must grant the Linux user running the MongoDB service read permissions on the keytab file. Take note of the full path of the keytab file location.

3

Connect to the MongoDB server.

Connect to the MongoDB server using the mongo shell using the --host and --port options.

mongo --host <hostname> --port <port>

If your MongoDB server currently enforces authentication, you must authenticate to the admin database as a user with role management privileges, such as those provided by userAdmin or userAdminAnyDatabase. Include the appropriate --authenticationMechanism for the MongoDB server’s configured authentication mechanism.

mongo --host <hostname> --port <port> --username <user> --password <pass> --authenticationDatabase="admin" --authenticationMechanism="<mechanism>"

Note

For Windows MongoDB deployments, you should replace mongo with mongo.exe

4

Create user administrative role.

To manage MongoDB users using AD, you need to create at least one role on the admin database that can create and manage roles, such as those provided by userAdmin or userAdminAnyDatabase.

The role’s name must exactly match the Distinguished Name of an AD group. The group must have at least one AD user as a member.

Given the available Active Directory groups,the following operation:

  • Creates a role named for the AD group CN=dba,CN=Users,DC=example,DC=com, and
  • Assigns it the userAdminAnyDatabase role on the admin database.
var admin = db.getSiblingDB("admin")
admin.createRole(
   {
     role: "CN=dba,CN=Users,DC=example,DC=com",
     privileges: [],
     roles: [ "userAdminAnyDatabase" ]
   }
)

You could alternatively grant the userAdmin role for each database the user should have user administrative privileges on. These roles provide the necessary privileges for role creation and management.

Important

Consider applying the principle of least privilege when configuring MongoDB roles, AD groups, or group membership.

5

Create a MongoDB configuration file.

A MongoDB configuration file is a plain-text YAML file with the .conf file extension.

  • If you are upgrading an existing MongoDB deployment, copy the current configuration file and work from that copy.
  • (Linux Only) If this is a new deployment and you used your platform’s package manager to install MongoDB Enterprise, the installation includes the /etc/mongod.conf default configuration file. Use that default configuration file, or make a copy of that file to work from.
  • If no such file exists, create an empty file with the .conf extension and work from that new configuration file.
6

Configure MongoDB to connect to Active Directory`.

In the MongoDB configuration file, set security.ldap.servers to the host and port of the AD server. If your AD infrastructure includes multiple AD servers for the purpose of replication, specify the host and port of the servers as a comma-delimited list to security.ldap.servers.

Example

To connect to an AD server located at activedirectory.example.net, include the following in the configuration file:

security:
  ldap:
    servers: "activedirectory.example.net"

MongoDB must bind to the AD server to perform queries. By default, MongoDB uses the simple authentication mechanism to bind itself to the AD server.

Alternatively, you can configure the following settings in the configuration file to bind to the AD server using SASL:

This tutorial uses the default simple LDAP authentication mechanism.

7

Configure MongoDB for Kerberos authentication.

In the MongoDB configuration file, set security.authorization to enabled and setParameter authenticationMechanisms to GSSAPI

To enable authentication via Kerberos, include the following in the configuration file:

security:
  authorization: "enabled"
setParameter:
  authenticationMechanisms: "GSSAPI"
8

Configure LDAP Query Template for authorization.

In the MongoDB configuration file, set security.ldap.authz.queryTemplate to an RFC4516 formatted LDAP query URL template.

In the template, you can use either:

  • {USER} placeholder to substitute the authenticated username into the LDAP query URL.
  • {PROVIDED_USER} placeholder to substitute the supplied username, i.e. before either authentication or LDAP transformation, into the LDAP query. (Available starting in version 4.2)

Design the query template to retrieve the user’s groups.

Note

A full description of RFC4515, RFC4516, or AD queries is out of scope for this tutorial. The queryTemplate provided in this tutorial is an example only, and may not be applicable for your specific AD deployment.

Example

The following query template returns any groups that list {USER} as a member, following recursive group memberships. This LDAP query assumes that group objects track user membership by storing full user Distinguished Name (DN) using the member attribute. The query includes the AD specific matching rule OID 1.2.840.113556.1.4.1941 for LDAP_MATCHING_RULE_IN_CHAIN. This matching rule is an AD specific extension to LDAP search filters.

security:
  ldap:
    authz:
      queryTemplate:
        "DC=example,DC=com??sub?(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={USER}))"

Using the query template, MongoDB substitutes {USER} with the authenticated username to query the LDAP server.

For example, a user authenticates as CN=sam,CN=Users,DC=dba,DC=example,DC=com. MongoDB creates an LDAP query based on the queryTemplate, substituting the {USER} token with the authenticated username. The Active Directory server performs a recursive group lookup for any group that either directly or transitively lists the user as a member. Based on the Active Directory groups, the AD server returns CN=dba,CN=Users,DC=example,DC=com and CN=engineering,CN=Users,DC=example,DC=com.

MongoDB maps each returned group DN to a role on the admin database. For each mapped group DN, if there is an existing role on the admin database whose name exactly matches the DN, MongoDB grants the user the roles and privileges assigned to that role.

The matching rule LDAP_MATCHING_RULE_IN_CHAIN requires providing the full DN of the authenticating user. Since Kerberos requires authenticating with a user’s userPrincipalName, you must transform the incoming usernames into DNs using security.ldap.userToDNMapping. The next step provides guidance on transforming incoming usernames to support the queryTemplate.

9

Transform incoming usernames for authentication via Active Directory.

In the MongoDB configuration file, set userToDNMapping to transform the authenticating user’s provided username into an AD DN to support the queryTemplate.

Example

The following userToDNMapping configuration uses the match regular expression filter to capture the provided username. MongoDB inserts the captured username into the ldapQuery query template before executing the query.

security:
  ldap:
    userToDNMapping:
      '[
         {
            match : "(.+)",
            ldapQuery: "DC=example,DC=com??sub?(userPrincipalName={0})"
         }
    ]'

You must modify the given sample configuration to match your deployment. For example, the ldapQuery base DN must match the base DN which contains your user entities. Other modifications may be necessary to support your AD deployment.

Example

A user authenticates as alice@ENGINEERING.EXAMPLE.COM. MongoDB first applies any transformations specified in userToDNMapping. Based on the provided configuration, MongoDB captures the username in the match stage and executes an LDAP query:

DC=example,DC=com??sub?([email protected])

Based on the configured Active Directory users, the AD server should return CN=alice,CN=Users,DC=engineering,DC=example,DC=com.

MongoDB then executes the LDAP query configured in queryTemplate, replacing the {USER} token with the transformed username CN=alice,CN=Users,DC=engineering,DC=example,DC=com.

Important

If you use userToDNMapping’s substitution parameter to transform the group name, the result of the substitution must be an RFC4514 escaped string.

10

Configure query credentials.

MongoDB requires credentials for performing queries on the AD server.

Configure the following settings in the configuration file:

security:
  ldap:
    bind:
      queryUser: "[email protected]"
      queryPassword: "secret123"

On Windows MongoDB servers, you can set security.ldap.bind.useOSDefaults to true to use the credentials of the OS user instead of queryUser and queryPassword.

The queryUser must have permission to perform all LDAP queries on behalf of MongoDB.

11

Optional: Add additional configuration settings.

Include additional options as required for your configuration. For instance, if you wish remote clients to connect to your deployment or your deployment members are run on different hosts, specify the net.bindIp setting. For more information, see Localhost Binding Compatibility Changes.

12

Start the MongoDB server with Kerberos authentication and Active Directory authorization.

Start the MongoDB server with the --config option, specifying the path to the configuration file created during this procedure. If the MongoDB server is currently running, make the appropriate preparations to stop the server.

Linux MongoDB Servers

On Linux, you must specify the KRB5_KTNAME environmental variable, specifying the path to the keytab file for the MongoDB server.

env KRB5_KTNAME <path-to-keytab> mongod --config <path-to-config-file>

Microsoft Windows MongoDB Servers

On Windows, you must start the MongoDB server as the service principal account as configured earlier in the procedure:

mongod.exe --config <path-to-config-file>
13

Connect to the MongoDB server.

Connect to the MongoDB server, authenticating as a user whose direct or transitive group membership corresponds to a MongoDB role on the admin database with userAdmin, userAdminAnyDatabase, or a custom role with equivalent privileges.

Use the mongo shell to authenticate to the MongoDB server, set the following options:

Example

Previously in this procedure, you configured the dn:CN=dba,CN=Users,DC=example,DC=com role on the admin database with the required permissions. This role corresponds to an AD group. Based on the configured AD users, you can authenticate as the user sam@dba.example.com and receive the required permissions.

mongo --username [email protected] --password  --authenticationMechanisms="GSSAPI" --authenticationDatabase "$external" --host <hostname> --port <port>

If you do not specify the password to the -p command-line option, the mongo shell prompts for the password.

Windows MongoDB deployments must use mongo.exe instead of mongo.

Given the configured Active Directory users, the user authenticates successfully and receives the appropriate permissions.

Note

If you want to authenticate as an existing non-$external user, set --authenticationMechanism to a SCRAM authentication mechanism (e.g. SCRAM-SHA-1 or SCRAM-SHA-256). This requires that the MongoDB server’s setParameter authenticationMechanisms includes SCRAM-SHA-1 and/or SCRAM-SHA-256 as appropriate.

14

Create roles for mapping returned AD groups.

For each group on the AD server you wish to use for MongoDB authorization, you must create a matching role on the MongoDB server’s admin database.

Example

The following operation creates a role named after the AD group DN CN=PrimaryApplication,CN=Users,DC=example,DC=com, assigning roles and privileges appropriate to that group:

db.getSiblingDB("admin").createRole(
   {
     role: "CN=PrimaryApplication,CN=Users,DC=example,DC=com",
     privileges: [],
     roles: [
       { role: "readWrite", db: "PrimaryApplication" }
     ]
   }
)

Given the configured Active Directory groups, MongoDB grants a user authenticating as either sam@DBA.EXAMPLE.COM or alice@ENGINEERING.EXAMPLE.COM the readWrite role on the PrimaryApplication database.

Note

To manage roles on the admin database, you must be authenticated as a user with userAdmin on admin, userAdminAnyDatabase, or a custom role on with equivalent privileges.

15

Optional: Transition existing users from $external to the Active Directory server.

If upgrading an existing installation with users configured on the $external database, you must meet the following requirements for each user to ensure access after configuring MongoDB for Kerberos authentication and AD authorization:

  • User has a corresponding user object on the AD server.
  • User has membership in the appropriate groups on the AD server.
  • MongoDB contains the roles on the admin database named for the user’s AD groups, such that the authorized user retains its privileges.

Example

The following user exists on the $external database:

{
  user : "[email protected]",
  roles: [
    { role : "read", db : "web_analytics" },
    { role : "read", db : "PrimaryApplication" }
  ]
}

Assuming the user belongs to the AD group CN=marketing,CN=Users,DC=example,DC=com, the following operation creates a matching role with the appropriate privileges:

db.getSiblingDB("admin").createRole(
   {
     role: "CN=marketing,CN=Users,DC=example,DC=com",
     privileges: [],
     roles: [
       { role: "read", db: "web_analytics" }
       { role: "read", db: "PrimaryApplication" }
     ]
   }
)

Based on the configured queryTemplate, MongoDB authorizes any user who has direct or transitive membership in the CN=marketing,CN=Users,DC=example,DC=com group to perform read operations on the web_analytics and PrimaryApplication databases.

Important

When configuring a role for a corresponding AD group, remember that all users with membership in that group can receive the assigned roles and privileges. Consider applying the principle of least privilege when configuring MongoDB roles, AD groups, or group membership.

If you want to continue allowing users on non-$external databases to access MongoDB, you must include SCRAM authentication mechanism (e.g. SCRAM-SHA-1 and/or SCRAM-SHA-256) in the setParameter authenticationMechanisms configuration option.

setParameter:
  authenticationMechanisms: "GSSAPI,SCRAM-SHA-1,SCRAM-SHA-256"

Alternatively, transition non-$external users to AD by following the above procedure.

This procedure produces the following configuration file:

security:
   authorization: "enabled"
   ldap:
      servers: activedirectory.example.net"
      bind:
         queryUser: "[email protected]"
         queryPassword: "secret123"
      userToDNMapping:
         '[
            {
               match: "(.+)"
               ldapQuery: "DC=example,DC=com??sub?(userPrincipalName={0})"
            }
         ]'
      authz:
         queryTemplate: "DC=example,DC=com??sub?(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={USER}))"
setParameter:
   authenticationMechanisms: "GSSAPI"

Important

The given sample configuration requires modification to match your AD schema, directory structure, and configuration. You may also require additional configuration file options for your deployment.

For more information on configuring roles and privileges, see:

Testing and Verification

After completing the configuration steps, you can validate your configuration with the mongokerberos tool.

Introduced alongside MongoDB 4.4, mongokerberos provides a convenient method to verify your platform’s Kerberos configuration for use with MongoDB, and to test that Kerberos authentication from a MongoDB client works as expected. See the mongokerberos documentation for more information.

mongokerberos is available in MongoDB Enterprise only.