Purpose
Here I will install mongo and set it up in a way where an user can only read and write a single collection or multiple collection but not all.
As a result it will increase security of the db.
Steps
Install mongodb
docker run -dit --name mongo -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=mongoAdmin33 mongo
Go into the docker container's mongosh
docker exec -it mongo bash -c "mongosh mongodb://admin:mongoAdmin33@localhost:27017/?authSource=admin"
Use this command and see that all the dbs are visible
show dbs;
It should show 3 collections like this -
Switch to a db using
use appleCollection;
Insert some data
db.apples.insertMany([
{
title: "Green Apple"
},
{
title: "Red Apple"
},
{
title: "Black Apple"
}
])
Create an user and give him read write access for only this collection
db.createUser(
{
user: "apple_admin",
pwd: "apple_admin_pass",
roles: [ "readWrite", "dbAdmin" ]
}
)
It should say
Exit from the current mongosh using
exit
Login into mongosh using the new apple admin account
docker exec -it mongo bash -c "mongosh mongodb://apple_admin:apple_admin_pass@localhost:27017/?authSource=appleCollection"
Please notice that we are using appleCollection
as the auth source.
Now use the command to see dbs;
show dbs;
Only one db should be visible.
Select data from this db.
db.apples.find({});
Switch to a different database
use randomDatabase;
Query this database and it should show error.
show collections
Reference
This was one of my projects that I tried out first here. Here you can also find how to give a user multiple database’s permission.
devops-notes/61. setup mongodb and give specific user permission to specific collection. I will update the github if I find something.
[Github]Giving user permission to specific database
Enjoy and let me know if any problem occurs.
Top comments (0)