Database Reference
In-Depth Information
■
if you enable authentication before adding the admin users, you will only be able to access your database
via localhost, meaning a connection made from the machine hosting the mongoDb instance. this is a security feature
designed to allow administrators to create users after having enabled authentication.
Note
Adding an Admin User
Adding the
admin
user is as simple as changing to the
admin
database and using the
addUser()
function:
$mongo
> use admin
> db.addUser({user : "admin", pwd: "pass", roles: [ "readWrite", "dbAdmin" ] })
{
"user" : "admin",
"pwd" : "e4e538f5dcb52537cad02bbf8491693c",
"roles" : [
"readWrite",
"dbAdmin"
],
"_id" : ObjectId("5239915b1ce3dc1efebb3c84")
}
You only need to add a single
admin
user at this point; once that user is defined, you can use it to add other
admin
users to the
admin
database or normal users to any other database.
Enabling Authentication
Now you need to alter your server's configuration to enable authentication. Do so by stopping your server and adding
--auth
to the startup parameters.
If you installed MongoDB with a packaged installer such as
yum
or Aptitude, then typically you can edit
/etc/
mongodb.conf
to enable
auth=true
. Next, you can use the following command to restart the server and enable
authentication:
$sudo service mongodb restart
In addition to
auth
you can also use a
keyfile
, a file that contains a preshared key of some description, which is
used to confirm communication between MongoDB nodes. To create a keyfile, just create a simple file with a phrase
or string in it to be used. Then add the option
keyfile=/path/to/keyfile
just as you did with
auth
. You can even
remove the old
auth=true
option, as running with
keyfile
implies
auth
.
Authenticating in the mongo Console
Before you can run restricted commands in the
admin
database, you will need to be authenticated as an
admin
user, as
in the following example:
$mongo
> use admin
switched to db admin
>show collections