mongo .js script cannot authorize against non-admin database as admin

599 views
Skip to first unread message

harryb

unread,
Mar 8, 2012, 7:21:25 AM3/8/12
to mongodb-user
I was having trouble writing a script to play into mongo to create a
new database on an authenticated server.

My problem was that I needed to authenticate as admin and then do some
actions on a new database.

Assuming I have already created an admin account "myadmin" with
password "myadmin!"...

Naively I thought I could do it like this:
db = connect("NewDB");
db.auth("myadmin","myadmin!");

this fails because myadmin is not a user in the database NewDB.

Trying this also didn't work:
db = connect("admin");
db.auth("myadmin","myadmin!");
db = connect("NewDB");

Although the first connect authenticates ok against admin, the second
connect opens a new connection and the authentication isn't carried
over.

What you really need to do is:
db = connect("admin");
db.auth("myadmin","myadmin!");
db = db.getMongo().getDB("NewDB");

I only found this out by poking around in the shell sources for the
"use" command. Some mention of this gotcha should be made on the shell
scripting page.

-- Harry

Nat

unread,
Mar 8, 2012, 7:53:47 AM3/8/12
to mongod...@googlegroups.com
Did you try db.getSisterDb()


> db.getSisterDB("admin").auth("user", "pass");
1
> db.mytest.save({"something": "here});

harryb

unread,
Mar 8, 2012, 10:02:08 AM3/8/12
to mongodb-user
Errm, no I didn't. Thanks for the useful tip. getSisterDB isn't
mentioned in the security and authentication section. I guess at least
one of these should be?

-- Harry

Tad Marshall

unread,
Mar 9, 2012, 10:07:25 AM3/9/12
to mongodb-user
Thanks for the note! We have new documentation in progress and we
will try to clarify the steps on the http://www.mongodb.org/display/DOCS/Security+and+Authentication
page to make this more clear.

Reading shell source code is a great way to see ways of approaching
doing things. It isn't possible for the documentation to give
examples of everything that can be accomplished using JavaScript and
MongoDB's built-in functions, but if there is a command that "almost"
does what you want you may see how you can do it yourself by looking
at how the shell does the "almost right for you" thing. You probably
know that typing a function call but leaving off the parentheses at
the end will display the code for you.

> db.getSisterDB
function (name) {
return this.getMongo().getDB(name);
}
> db.getSiblingDB
function (name) {
return this.getMongo().getDB(name);
}
>

So you can see that db.getSisterDB and db.getSiblingDB do the same
thing. As Nat said, these functions gives you a way of referencing
another database directly.

-- Tad Marshall
Reply all
Reply to author
Forward
0 new messages