In this post I will demonstrate how to setup 2 read only users in MongoDB, one user that will have access to one MongoDB Database and all the Collections, and one user with access to one MongoDB Database and only one Collection.
First Method: Creating and Assigning the User
The first method we will create the user and assign it the read permissions that he needs. In this case read only access to the mytest db.
First logon to mongodb and switch to the admin database:
1 2 3 |
|
Now list the dbs:
1 2 3 |
|
List the collections and read the data from it for demonstration purposes:
1 2 3 4 5 6 7 8 |
|
Now create the user collectionreader that will have access to read all the collections from the database:
1 2 3 4 5 6 7 8 9 10 |
|
Exit and log out and log in with the new user to test the permissions:
1 2 3 4 5 6 7 8 9 10 |
|
Now lets try to write to a collection:
1 2 3 4 5 6 7 |
|
So we can see it works as expected.
Second Method: Create Roles and Assign Users to the Roles
In the second method, we will create the roles then assign the users to the roles. And in this scenario, we will only grant a user reader
access to one collection on a database. Login with the admin user:
1 2 |
|
First create the read only role myReadOnlyRole
:
1
|
|
Now create the user and assign it to the role:
1
|
|
Similarly, if we had an existing user that we also would like to add to that role, we can do that by doing this:
1
|
|
Logout and login with the reader user:
1 2 |
|
Now try to list the collections:
1 2 3 4 5 6 7 |
|
As we only have read (find) access on col2, lets try to read data from collection col1:
1 2 3 4 5 6 7 |
|
And finally try to read data from the collection we are allowed to read from:
1 2 |
|
And also making sure we cant write to that collection:
1 2 3 4 5 6 7 |
|
Assigning Permissions to Roles
If you later on want to add more permissions to the role, this can easily be done by using grantPrivilegesToRole()
:
1 2 3 |
|
To view the permissions for that role:
1
|
|
Resources:
- https://docs.mongodb.com/manual/tutorial/create-users/
- https://docs.mongodb.com/manual/core/collection-level-access-control/
- https://docs.mongodb.com/manual/reference/privilege-actions/
- https://sanderknape.com/2018/07/manage-custom-secrets-aws-secrets-manager/
- https://blog.mlab.com/2016/07/mongodb-tips-tricks-collection-level-access-control/
- https://studio3t.com/knowledge-base/articles/mongodb-users-roles-explained-part-1/