OPTIONS

Authenticate to MongoDB with the Java Driver

This page is a brief overview of authenticating to a MongoDB cluster with the MongoDB Java Driver using version 2.11.0 and above.

Normal Authentication

To authenticate as the user “user1” with a password of “password1”, defined in the “test” database:

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

// using release 2.13 or later
MongoCredential credential = MongoCredential.createCredential("user1", "test", "password1".toCharArray());

// using release 2.11 or 2.12
MongoCredential credential = MongoCredential.createMongoCRCredential("user1", "test", "password1".toCharArray());

MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credential));

In some cases you may need to authenticate as multiple users in different databases. For example, imagine a map/reduce job that reads from the database “first” and writes the results to the database “second”. You may have to authenticate one user defined in the “first” database and another in the “second”:

MongoCredential credentialOne = MongoCredential.createCredential("user1", "first", "password1".toCharArray());
MongoCredential credentialTwo = MongoCredential.createCredential("user2", "second", "password2".toCharArray());

MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credentialOne, credentialTwo));

Note

As of the 2.4 MongoDB release, this is no long necessary, since you are able to define a user in one database and delegate privileges for that user in another database.

Kerberos Authentication

Note

These features are only present in MongoDB Enterprise.

Important

The Java driver maintainers have only confirmed the content of this document on Linux using Java 6 and Java 7, on OS X using Java 7, and on Windows with SSPI using Java 7.

To authenticate to a MongoDB cluster using Kerberos, you must supply the Kerberos user name and specify the Kerberos authentication mechanism:

MongoCredential credential = MongoCredential.createGSSAPICredential("user1@MYREALM.ME");

MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credential));

Note

With Kerberos you specify neither the password not the database name.

To actually run a program that authenticates with Kerberos, you typically will need to specify several system properties so that the underlying GSSAPI Java libraries can acquire a Kerberos ticket:

java.security.krb5.realm=MYREALM.ME
java.security.krb5.kdc=mykdc.myrealm.me