mongodb authentication setting

The steps below to create authentication for mongodb assumes the mongodb was installed on mac os with homebrew, but shouldn’t be much of a difference other than the file locations.

Create a mongodb key file
[code language=”shell”]
cd ~
mkdir .keyfile
cd .keyfile
openssl rand -base64 741 > mongodb_keyfile
chmod 600 mongodb_keyfile
[/code]

Create a mongodb config file /usr/local/etc/mongod.conf and put these configurations. Change yourusername to yours.
[code language=”shell”]
security:
keyFile: /Users/yourusername/.keyfile/mongodb_keyfile
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: /usr/local/var/mongodb
net:
bindIp: 127.0.0.1
[/code]

Start mongodb with this command line and then shell into mongodb
[code language=”shell”]
mongod –config /usr/local/etc/mongod.conf &
mongo
[/code]

Create amdin user in mongodb shell and exit.
[code language=”shell”]
use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
);
exit;
[/code]

Shell back into mongodb with the above admin user
[code language=”shell”]
mongo –port 27017 -u admin -p password –authenticationDatabase admin
[/code]

Create user for a database called test, with read access to database test1, test2, test3, read and write access to test4
[code language=”javascript”]
use test
db.createUser(
{
user: "tester",
pwd: "password",
roles: [
{ role: "read", db: "test1" },
{ role: "read", db: "test2" },
{ role: "read", db: "test3" },
{ role: "readWrite", db: "test" }
]
}
);
[/code]

Shell into mongodb with the test user
[code language=”shell”]
mongo -u tester -p –authenticationDatabase test
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search