Authenticate to MongoDB with the Java Driver¶
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.
This page is a brief overview of authenticating to a MongoDB cluster with the MongoDB Java Driver using version 2.11.0 and above.
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; // ... 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.createMongoCRCredential("user1", "first", "password1".toCharArray()); MongoCredential credentialTwo = MongoCredential.createMongoCRCredential("user2", "second", "password2".toCharArray()); MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credentialOne, credentialTwo));
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.
These features are only present in MongoDB Enterprise.
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));
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:
javax.security.auth.useSubjectCredsOnly=false java.security.krb5.realm=MYREALM.ME java.security.krb5.kdc=mykdc.myrealm.me