Search This Blog

2020/12/03

MongoDb:Secure by enabling username & password for login

I am using Ubuntu & I already have mongodb installed with default setting.
To login to mongo shell I usually run
mongosh
command without any username ot password.Now we will make changes so that
useranme & password become essential to login to mongo-shell.

For that purpose first login to mongodb simply by calling
mongosh

In shell run
use admin;

List users using
show users;

Output:
[
{
_id: 'admin.dev',
userId: UUID('1cbde7e7-8e19-45c9-87b8-7fa9e4679cbd'),
user: 'dev',
db: 'admin',
roles: [
{ role: 'userAdminAnyDatabase', db: 'admin' },
{ role: 'readWriteAnyDatabase', db: 'admin' }
],
mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
},
{
_id: 'admin.root',
userId: UUID('e9470ae4-18c5-42e4-9b47-ba9b3396fb98'),
user: 'root',
db: 'admin',
roles: [
{ role: 'readWriteAnyDatabase', db: 'admin' },
{ role: 'userAdminAnyDatabase', db: 'admin' }
],
mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
}
]

Note:Your Output may vary.

Here there is no custom user defined.we will defined one named "sangram" in it.

to create user with password run following query:

db.createUser(
{
user: "sangram",
pwd: "sangram#81",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
);

please change name of user (user) & password (pwd) as per your choice

Now to grant access to user "sangram" to say "phenixDb" database.In
admin database only run following query.

db.grantRolesToUser(
"sangram",
[
{ role: "readWrite", db: "phenixDb" }, // Read and write access
{ role: "dbAdmin", db: "phenixDb" } // Database admin access
]
);


Then open configuration file "/etc/mongod.conf" as follows

sudo nano /etc/mongod.conf
search for word "security"
change
autorization:"disabled"
to
autorization:"enabled"

don't forgot to uncomment security by removing # before it if any,

It should look as follows

security:
authorization: "enabled"

Save file.

Restart mongodb service as follows

sudo systemctl restart mongod

You can check status of mongod service as

sudo systemctl status mongod

Now you can connect to mongodb using username & password as follows

mongosh --port 27017 -u "sangram" -p "sangram#81"
--authenticationDatabase "admin"

In my case it login into database "test" after running this command.

No comments:

Post a Comment