Database Reference
In-Depth Information
The authentication API
To g e t s t a r t e d w it h a u t h e n t ic a t i o n , f ir s t c r e a t e a n a d m in u s e r b y s w i t c h i n g t o t h e admin
database and running db.addUser() . This method takes two arguments: a username
and a password:
> use admin
> db.addUser("boss", "supersecret")
Admin users can create other users and access all databases on the server. With an
admin user in place, you can enable authentication. To do so, restart the mongod
instance with the --auth option:
$ mongod --auth
Now only authorized users will be able to access the database. Restart the shell, and
then log in as the admin user with the db.auth() method:
> use admin
> db.auth("boss", "supersecret")
You can now create users for individual databases. If you want to create read-only
users, add true as the last argument to the db.addUser() method. Here you add two
users for the stocks database. The first has all permissions; the second can only read
from the database:
> use stocks
> db.addUser("trader", "moneyfornuthin")
> db.addUser("read-only-trader", "foobar", true)
Now, just three users—boss, trader, and read-only-trader—can access the stocks data-
base. If you ever want to see a list of all users with access to a given database, query the
system.users collection:
> db.system.users.find()
{ "_id" : ObjectId("4d82100a6dfa7bb906bc4df7"),
"user" : "trader", "readOnly" : false,
"pwd" : "e9ee53b89ef976c7d48bb3d4ea4bffc1" }
{ "_id" : ObjectId("4d8210176dfa7bb906bc4df8"),
"user" : "read-only-trader", "readOnly" : true,
"pwd" : "c335fd71fb5143d39698baab3fdc2b31" }
Deleting a user from this collection will revoke the user's access to the database. If you
prefer a helper, you can use the shell's db.removeUser() method, which does the
same thing.
You don't need to explicitly log out; terminating the connection (closing the shell)
will accomplish that just fine. But there is a command for logging out if you need it:
> db.runCommand({logout: 1})
Naturally, you can leverage all of the authentication logic we've been exploring here
using the drivers. Check your driver's API for the details.
Search WWH ::




Custom Search