Authenticate and Authorize Users Using Active Directory via Native LDAP

Starting in version 3.4, MongoDB Enterprise provides support viaplatform LDAP libraries for proxying authentication and authorizationrequests to a specified Lightweight Directory Access Protocol (LDAP)service such as Active Directory (AD).

This tutorial describes how to configure MongoDB to perform authenticationand authorization through an Active Directory (AD) server via the platformlibraries.

Note

For MongoDB 4.2 (and 4.0.9) Enterprise binaries linked againstlibldap (such as when running on RHEL), access to thelibldap is synchronized, incurring some performance/latencycosts.

For MongoDB 4.2 (and 4.0.9) Enterprise binaries linked againstlibldap_r, there is no change in behavior from earlier MongoDBversions.

To avoid the automatic synchronization with libldap, you maywish to link to libldap_r. Contact support forassistance.

Prerequisites

Important

Thoroughly familiarize yourself with the following subjects before proceeding:

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

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

Considerations

This tutorial explains configuring MongoDB for ADauthentication and authorization.

To perform this procedure on your own MongoDB server, you must modify thegiven procedures with respect to your own specific infrastructure, especiallyActive Directory configurations, constructing ADqueries, 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 MongoDBserver 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 andcan create a copy of the certificates on the MongoDB server.

User Names

Changed in version 3.6.3: To use sessions with $external authentication users (i.e.Kerberos, LDAP, x.509 users), the usernames cannot be greaterthan 10k bytes.

Example Active Directory Schema

This tutorial uses the following example AD objectsas the basis for the provided queries, configurations, and output. Each objectshows only a subset of the possible attributes.

User Objects

  1. dn:CN=bob,CN=Users,DC=marketing,DC=example,DC=com
  2. userPrincipalName: bob@marketing.example.com
  3. memberOf: CN=marketing,CN=Users,DC=example,DC=com
  4.  
  5. dn:CN=alice,CN=Users,DC=engineering,DC=example,DC=com
  6. userPrincipalName: alice@engineering.example.com
  7. memberOf: CN=web,CN=Users,DC=example,DC=com
  8. memberOf: CN=PrimaryApplication,CN=Users,DC=example,DC=com
  9.  
  10. dn:CN=sam,CN=Users,DC=dba,DC=example,DC=com
  11. userPrincipalName: sam@dba.example.com
  12. memberOf: CN=dba,CN=Users,DC=example,DC=com
  13. memberOf: CN=PrimaryApplication,CN=Users,DC=example,DC=com
  14.  
  15. dn:CN=joe,CN=Users,DC=analytics,DC=example,DC=com
  16. userPrincipalName: joe@analytics.example.com
  17. memberof: CN=marketing,CN=Users,DC=example,DC=com

Group Objects

  1. dn:CN=marketing,CN=Users,DC=example,DC=com
  2. member:CN=bob,CN=Users,DC=marketing,DC=example,DC=com
  3. member:CN=joe,CN=Users,DC=analytics,DC=example,DC=com
  4.  
  5. dn:CN=engineering,CN=Users,DC=example,DC=com
  6. member:CN=web,CN=Users,DC=example,DC=com
  7. member:CN=dba,CN=users,DC=example,DC=com
  8.  
  9. dn:CN=web,CN=Users,DC=example,DC=com
  10. member:CN=alice,CN=Users,DC=engineering,DC=example,DC=com
  11.  
  12. dn:CN=dba,CN=Users,DC=example,DC=com
  13. member:CN=sam,CN=Users,DC=dba,DC=example,DC=com
  14.  
  15. dn:CN=PrimaryApplication,CN=Users,DC=example,DC=com
  16. member:CN=sam,CN=Users,DC=dba,DC=example,DC=com
  17. 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 theAD server. The credentials provided must havesufficient privileges on the AD server for supporting queries related tosecurity.ldap.userToDNMapping orsecurity.ldap.authz.queryTemplate.

Replica Sets

MongoDB LDAP authorization requires everymongod in the replicaset to be on at least MongoDB 3.4.0 or later.

Sharded Clusters

MongoDB LDAP authorization requires everymongod andmongos in the sharded cluster to be on at least MongoDB 3.4.0 orlater.

Procedure

Configure TLS/SSL for the server running MongoDB

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

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

Your platform’s package manager creates the ldap.conf file whileinstalling MongoDB Enterprise’s libldap dependency. For completedocumentation on the configuration file or the referenced options, seeldap.conf.

On Microsoft Windows, load the AD server’s Certificate Authority (CA) certificates with theplatform’s credential management tool. The exact credential management toolis 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 theActive Directory server.

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

Warning

Setting transportSecurity to none transmitsplaintext information, including user credentials, between MongoDB andthe AD server.

Connect to the MongoDB server.

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

  1. mongo --host <hostname> --port <port>

If your MongoDB server currently enforces authentication, you mustauthenticate to the admin database as a user with role managementprivileges, such as those provided by userAdmin oruserAdminAnyDatabase. Include the appropriate—authenticationMechanism for theMongoDB server’s configured authentication mechanism.

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

Note

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

Create user administrative role.

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

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 groupCN=dba,CN=Users,DC=example,DC=com, and
  • Assigns it the userAdminAnyDatabase role on the admindatabase.
  1. var admin = db.getSiblingDB("admin")
  2. admin.createRole(
  3. {
  4. role: "CN=dba,CN=Users,DC=example,DC=com",
  5. privileges: [],
  6. roles: [ "userAdminAnyDatabase" ]
  7. }
  8. )

You could alternatively grant the userAdmin role for eachdatabase the user should have user administrative privileges on. These rolesprovide the necessary privileges for role creation and management.

Important

Consider applying the principle of least privilegewhen configuring MongoDB roles, AD groups, orgroup membership.

Create a MongoDB configuration file.

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

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

Configure MongoDB to connect to Active Directory.

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

You must also enable LDAP authentication by settingsecurity.authorization to enabled and setParameterauthenticationMechanisms to PLAIN

Example

To connect to an AD server located atactivedirectory.example.net, include the following in theconfiguration file:

  1. security:
  2. authorization: "enabled"
  3. ldap:
  4. servers: "activedirectory.example.net"
  5. setParameter:
  6. authenticationMechanisms: 'PLAIN'

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

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

This tutorial uses the default simple LDAP authentication mechanism.

Configure LDAP Query Template for authorization.

In the MongoDB configuration file, setsecurity.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 intothe LDAP query URL.
  • {PROVIDEDUSER} placeholder to substitute the supplied username,i.e. before either authentication or LDAP transformation, into theLDAP query. (_Available starting in version 4.2)

Note

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

Example

The following query template returns any groups that list {USER} as amember, following recursive group memberships. This LDAP query assumesthat group objects track user membership by storing full userDistinguished Name (DN) using the member attribute. The queryincludes the AD specific matching rule OID1.2.840.113556.1.4.1941 for LDAP_MATCHING_RULE_IN_CHAIN.aspx). Thismatching rule is an AD specific extension toLDAP search filters.

  1. security:
  2. ldap:
  3. authz:
  4. queryTemplate:
  5. "DC=example,DC=com??sub?(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={USER}))"

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

For example, a user authenticates asCN=sam,CN=Users,DC=dba,DC=example,DC=com. MongoDB creates an LDAPquery based on the queryTemplate,substituting the {USER} token with the authenticated/transfored username. The ActiveDirectory server performs a recursive group lookup for any group thateither directly or transitively lists the user as a member. Based on theActive Directory groups, theAD server returnsCN=dba,CN=Users,DC=example,DC=com andCN=engineering,CN=Users,DC=example,DC=com.

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

The matching rule LDAP_MATCHING_RULE_IN_CHAIN requires providing thefull DN of the authenticating user. If usersauthenticate using a different username format, such as their userprincipal name, you must transform the incoming usernames into DNs using security.ldap.userToDNMapping.

Optional: Transform incoming usernames for authentication via Active Directory,

If your users authenticate with a username that is not a full LDAP DN,you may need to transform the username to support LDAP authenticationor authorization. MongoDB uses the transformed username for bothauthentication and authorization.

In the MongoDB configuration file, setuserToDNMapping to transform the authenticatinguser’s provided username into an AD DN to supportthe queryTemplate.

Example

Given the configured queryTemplate,users must authenticate with their full LDAP DN. If users insteadauthenticate using their userPrincipalName, then a transformationmust be applied to convert the provided username to a full LDAP DN.

The following userToDNMapping configurationuses the match regular expression filter to capture the providedusername. MongoDB inserts the captured username into the ldapQueryquery template before executing the query.

  1. security:
  2. ldap:
  3. userToDNMapping:
  4. '[
  5. {
  6. match : "(.+)",
  7. ldapQuery: "DC=example,DC=com??sub?(userPrincipalName={0})"
  8. }
  9. ]'

The Active Directory server returns the full LDAP DN associated to theuser object with a matching userPrincipalName. MongoDB can then usethis transformed username for authentication and authorization.

You must modify the given sample configuration to match your deployment. Forexample, the ldapQuery base DN must matchthe 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 firstapplies any transformations specified inuserToDNMapping. Based on the providedconfiguration, MongoDB captures the username in the match stage andexecutes an LDAP query:

  1. DC=example,DC=com??sub?(userPrincipalName=alice@ENGINEERING.EXAMPLE.COM)

Based on the configured Active Directoryusers, the AD server should returnCN=alice,CN=Users,DC=engineering,DC=example,DC=com.

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

Important

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

Configure query credentials.

MongoDB requires credentials for performing queries on the AD server.

Configure the following settings in the configuration file:

  1. security:
  2. ldap:
  3. bind:
  4. queryUser: "mongodbadmin@dba.example.com"
  5. queryPassword: "secret123"

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

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

Optional: Add additional configuration settings.

Add any additional configuration options required for your deployment.For example, you can specify your desired storage.dbPath orchange the default net.port number.

Starting in MongoDB 3.6, mongod and mongosbind to localhost by default. If the members of your deployment arerun on different hosts or if you wish remote clients to connect toyour deployment, you must specify the net.bindIp setting.For more information, see Localhost Binding Compatibility Changes.

Start the MongoDB server with Active Directory authentication and authorization.

Start the MongoDB server with the —config option, specifying thepath to the configuration file created during this procedure. If theMongoDB server is currently running, make the appropriate preparations tostop the server.

  1. mongod --config <path-to-config-file>

Windows MongoDB deployments must usemongod.exe instead of mongod.

Connect to the MongoDB server.

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

Use the mongo shell to authenticate to the MongoDBserver, set the following options:

Example

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

  1. mongo --username sam@DBA.EXAMPLE.COM --password --authenticationMechanism 'PLAIN' --authenticationDatabase '$external' --host <hostname> --port <port>

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

Windows MongoDB deployments must usemongo.exe instead of mongo.

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

Note

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

Create roles for mapping returned AD groups.

For each group on the AD server you wish to usefor MongoDB authorization, you must create a matching role on the MongoDBserver’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:

  1. db.getSiblingDB("admin").createRole(
  2. {
  3. role: "CN=PrimaryApplication,CN=Users,DC=example,DC=com",
  4. privileges: [],
  5. roles: [
  6. { role: "readWrite", db: "PrimaryApplication" }
  7. ]
  8. }
  9. )

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

Note

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

Transition existing users from $external to the ActiveDirectory server

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

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

Example

The following user exists on the $external database:

  1. {
  2. user : "joe@ANALYTICS.EXAMPLE.COM",
  3. roles: [
  4. { role : "read", db : "web_analytics" },
  5. { role : "read", db : "PrimaryApplication" }
  6. ]
  7. }

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

  1. db.getSiblingDB("admin").createRole(
  2. {
  3. role: "CN=marketing,CN=Users,DC=example,DC=com",
  4. privileges: [],
  5. roles: [
  6. { role: "read", db: "web_analytics" }
  7. { role: "read", db: "PrimaryApplication" }
  8. ]
  9. }
  10. )

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

Important

When configuring a role for a corresponding ADgroup, remember that all users with membership in that group canreceive the assigned roles and privileges. Consider applying theprinciple of least privilegewhen configuring MongoDB roles, AD groups,or group membership.

If you want to continue allowing users on non-$external databasesto access MongoDB, you must include SCRAM authentication mechanism(e.g. SCRAM-SHA-1 and/or SCRAM-SHA-256) in thesetParameterauthenticationMechanismsconfiguration option. For example:

  1. setParameter:
  2. authenticationMechanisms: "PLAIN,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:

  1. security:
  2. authorization: "enabled"
  3. ldap:
  4. servers: "activedirectory.example.net"
  5. bind:
  6. queryUser: "mongodbadmin@dba.example.com"
  7. queryPassword: "secret123"
  8. userToDNMapping:
  9. '[
  10. {
  11. match: "(.+)",
  12. ldapQuery: "DC=example,DC=com??sub?(userPrincipalName={0})"
  13. }
  14. ]'
  15. authz:
  16. queryTemplate: "DC=example,DC=com??sub?(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={USER}))"
  17. setParameter:
  18. authenticationMechanisms: "PLAIN"

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

For more information on configuring roles and privileges, see: