Skip to content

Instantly share code, notes, and snippets.

@dmregister
Created April 13, 2015 16:39
Show Gist options
  • Save dmregister/346aa4402a6fae4f2d54 to your computer and use it in GitHub Desktop.
Save dmregister/346aa4402a6fae4f2d54 to your computer and use it in GitHub Desktop.
mongodb auth
//First user created
use admin
db.createUser(
{
user: "admintest",
pwd: "testing",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
//second user created
use admin
db.createUser(
{
user: "test_dbuser",
pwd: "testpass",
roles: [
{ role: "readWrite", db: "testingdb" }
]
}
)
//sample connection string
mongodb://test_dbuser:testpass@localhost:27017/testingdb.test
//rebuilds the connection
MongoCredential credential = MongoCredential.createMongoCRCredential(mongoClientUri.getUsername(), "admin", mongoClientUri.getPassword());
String mongoHost = mongoClientUri.getHosts().get(0);
MongoClient mongoClient = new MongoClient(new ServerAddress(mongoHost), Arrays.asList(credential));
//Always throws exception
com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "auth failed" , "code" : 18}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment