- Configure MongoDB with Kerberos Authentication and Active Directory Authorization
- Prerequisites
- Considerations
- Procedure
- Configure TLS/SSL for the server running MongoDB.
- (Windows only) Assign Service Principal Name to MongoDB Windows Service.
- (Linux only) Create keytab file for the MongoDB server.
- Connect to the MongoDB server.
- Create user administrative role.
- Create a MongoDB configuration file.
- Configure MongoDB to connect to Active Directory`.
- Configure MongoDB for Kerberos authentication.
- Configure LDAP Query Template for authorization.
- Transform incoming usernames for authentication via Active Directory.
- Configure query credentials.
- Optional: Add additional configuration settings.
- Start the MongoDB server with Kerberos authentication and Active Directory authorization.
- Connect to the MongoDB server.
- Create roles for mapping returned AD groups.
- Optional: Transition existing users from $external to the Active Directory server.
Configure MongoDB with Kerberos Authentication and Active Directory Authorization
New in version 3.4: MongoDB Enterprise supportsquerying an LDAP server for the LDAP groups to which an authenticated userbelongs. MongoDB maps the LDAP distinguished names (DN) of each returnedgroup to roles on the admin
database. MongoDB authorizesthe user based on the mapped roles and their associated privileges. SeeLDAP Authorization for more information.
MongoDB Enterprise supports authentication using a Kerberos service. Kerberos is an industry standard authentication protocolfor large client/server systems.
This tutorial describes how to configuring MongoDB to perform authenticationthrough a Kerberos server and authorization through an Active Directory (AD)server via the platform libraries.
Prerequisites
Important
Thoroughly familiarize yourself with the following subjects beforeproceeding:
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.
Setting up and configuring a Kerberos deployment is beyond the scope ofthis document. This tutorial assumes you have configured aKerberos service principal for eachmongod
and mongos
instance in your MongoDBdeployment, and you have a valid keytab file forfor each mongod
and mongos
instance.
For replica sets and sharded clusters, ensure that your configurationuses fully qualified domain names (FQDN) rather than IP addresses orunqualified hostnames. You must use the FQDN for GSSAPI to correctlyresolve the Kerberos realms and allow you to connect.
To verify MongoDB Enterprise binaries, pass the —version
command lineoption to the mongod
or mongos
:
- mongod --version
In the output from this command, look for the string modules:subscription
or modules: enterprise
to confirm your system hasMongoDB Enterprise.
Considerations
This tutorial explains configuring MongoDB for Kerberos authentication andAD authorization.
To perform this procedure on your own MongoDB server, you must modify thegiven procedures with respect to your own specific infrastructure, especiallyKerberos 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 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.
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
- dn:CN=bob,CN=Users,DC=marketing,DC=example,DC=com
- userPrincipalName: bob@marketing.example.com
- memberOf: CN=marketing,CN=Users,DC=example,DC=com
- dn:CN=alice,CN=Users,DC=engineering,DC=example,DC=com
- userPrincipalName: alice@engineering.example.com
- 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: sam@dba.example.com
- 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: joe@analytics.example.com
- 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 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 none
to disable TLS/SSL.
Warning
Setting transportSecurity
to none
transmitsplaintext information, including user credentials, between MongoDB andthe AD server.
(Windows only) Assign Service Principal Name to MongoDB Windows Service.
For MongoDB servers running on the Windowsoperating system, you must use setspn.exe.aspx) toassign the service principal name (SPN) to the account running the MongoDBservice.
- setspn.exe -S <service>/<fully qualified domain name> <service account name>
Example
For example, if a mongod
runs as a service named mongodb
onmongodbserver.example.com
with the service account namemongodb_dev@example.com
, the command to assign the SPN would look asfollows:
- setspn.exe -S mongodb/mongodbserver.example.com mongodb_dev@example.com
Note
Windows Server 2003 does not supportsetspn.exe -S
. For complete documentation on setspn.exe
, seesetspn.exe.aspx).
(Linux only) Create keytab file for the MongoDB server.
For MongoDB servers running on the Linux platform, you must ensure theserver has a copy of the keytab file specific to theMongoDB instance running on that server.
You must grant the Linux user running the MongoDB service read permissionson the keytab file. Take note of the full path of the keytab file location.
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 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.
- 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 group
CN=dba,CN=Users,DC=example,DC=com
, and - Assigns it the
userAdminAnyDatabase
role on theadmin
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 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
.
Example
To connect to an AD server located atactivedirectory.example.net
, include the following in theconfiguration file:
- security:
- ldap:
- servers: "activedirectory.example.net"
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
:
- Set
security.ldap.bind.method
tosasl
security.ldap.bind.saslMechanisms
, specifying a string ofcomma-separated SASL mechanisms the AD serversupports.
This tutorial uses the default simple
LDAP authentication mechanism.
Configure MongoDB for Kerberos authentication.
In the MongoDB configuration file, set security.authorization
toenabled and setParameter
authenticationMechanisms
to GSSAPI
To enable authentication via Kerberos, include the following inthe configuration file:
- security:
- authorization: "enabled"
- setParameter:
- authenticationMechanisms: "GSSAPI"
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 usernameinto the LDAP query URL.{PROVIDEDUSER}
placeholder to substitute the suppliedusername, 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 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.
- 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 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 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. SinceKerberos requires authenticating with a user’s userPrincipalName
, youmust transform the incoming usernames into DNsusing security.ldap.userToDNMapping
. The next step providesguidance on transforming incoming usernames to support thequeryTemplate
.
Transform incoming usernames for authentication via Active Directory.
In the MongoDB configuration file, setuserToDNMapping
to transform the authenticatinguser’s provided username into an AD DN to supportthe queryTemplate
.
Example
The following userToDNMapping
configurationuses the match
regular expression filter to capture the providedusername. 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. 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:
- DC=example,DC=com??sub?(userPrincipalName=alice@ENGINEERING.EXAMPLE.COM)
Based on the configured Active Directoryusers, the ADserver 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:
security.ldap.bind.queryUser
, specifying the Kerberos user themongod
ormongos
binds as for performing queries onthe AD server.security.ldap.bind.queryPassword
, specifying the password forthe specifiedqueryUser
.
- security:
- ldap:
- bind:
- queryUser: "mongodbadmin@dba.example.com"
- 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.
Include additional options as requiredfor your configuration. For instance, if you wish remote clients toconnect to your deployment or your deployment members are run ondifferent hosts, specify the net.bindIp
setting. For moreinformation, see Localhost Binding Compatibility Changes.
Start the MongoDB server with Kerberos authentication and Active Directory 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.
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 asthe service principal account as configured earlier in the procedure:
- mongod.exe --config <path-to-config-file>
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 admin
database with userAdmin
, userAdminAnyDatabase
,or a custom role with equivalent privileges.
Use the mongo
shell to authenticate to the MongoDBserver, set the following options:
—host
with the hostname of the MongoDB server—port
with the port of the MongoDB server—username
to the user’suserPrincipalName
—password
to the user’s password (or omit to have themongo
shell prompt for the password)—authenticationMechanism
to"GSSAPI"
—authenticationDatabase
to"$external"
Example
Previously in this procedure, you configured thedn:CN=dba,CN=Users,DC=example,DC=com
role on the admin
database withthe 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.
- mongo --username sam@DBA.EXAMPLE.COM --password --authenticationMechanisms="GSSAPI" --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 a SCRAM authentication mechanism (e.g. SCRAM-SHA-1
or SCRAM-SHA-256
). This requiresthat the MongoDB server’s setParameter
authenticationMechanisms
includes SCRAM-SHA-1
and/or SCRAM-SHA-256
as appropriate.
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:
- 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 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.
Optional: Transition existing users from $external to the Active Directory server.
If upgrading an existing installation with users configuredon the $external
database, you must meet the following requirementsfor each user to ensure access after configuring MongoDB forKerberos authentication and AD 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:
- {
- user : "joe@ANALYTICS.EXAMPLE.COM",
- roles: [
- { role : "read", db : "web_analytics" },
- { role : "read", db : "PrimaryApplication" }
- ]
- }
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:
- 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 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
databases toaccess MongoDB, you must include SCRAM authentication mechanism (e.g. SCRAM-SHA-1
and/or SCRAM-SHA-256
) in thesetParameter
authenticationMechanisms
configurationoption.
- 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: "mongodbadmin@dba.example.com"
- 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 mayalso require additional configuration file options for your deployment.
For more information on configuring roles and privileges, see: