User Management with MongoDB
- By : Mydatahack
- Category : DBA, Infrastructure
- Tags: DBA, MongoDB, User Management
MongoDB does not have authentication out of box. When you install it, the first thing you have to do is to create an admin user in the admin database and enable authentication.
After installation, you can get into MongoDB with the mongo command from the Mongo Shell.
Let’s create an admin user in the admin database. In MongoDB, the database you create your user is used for authentication only. It can have access privileges to other databases. It really does not matter which database you create a user unless you want to create a user who has access to only a particular database.
First of all, let’s create a root user & admin user. We will use admin user to create other credentials.
(1) Root and Admin User Creation
db.createUser({
user: "root",
pwd: "your_password",
roles: ["root"]
})
db.createUser({
user: "admin",
pwd: "your_password",
roles: ["readWriteAnyDatabase", "clusterAdmin",
"userAdminAnyDatabase", "dbAdminAnyDatabase"]
})
(2) Enable Authentication
Once the admin user is created, let’s restart MongoDB with authentication enabled. After restarting the DB server, you cannot do any operations if you are not an authenticated user. The better way is change the config file in this post.
Once the authentication is enabled, connect to database as admin
(3) User Creations
We will create 3 types of users below.
- Writer: access to read & write operations to all databases
- Readonly : access to read operations to all databases
- Special: Read access to all databases and write access to usermanaged
use admin
db.createUser ({
user: "writer",
pwd: "your_password",
roles: ["readWriteAnyDatabase"]
})
# (2) Create Readonly Credential
use admin
db.createUser ({
user: "readonly",
pwd: "your_password",
roles: ["readAnyDatabase"]
})
# (3) Create a special Credential
use admin
db.createUser(
{
user: "special",
pwd: "your_password",
roles:
[
{ role: "readWrite", db: "usermanaged" },
"readAnyDatabase"
]
}
)
(4) Test Credentials
Let’s test each users by logging into the database to see if you can do the desired operations. Make sure to specify the database (admin) where you created them as the first argument in the mongo command.
mongo admin --host localhost --port 27017 -u writer -p your_password
mongo admin --host localhost --port 27017 -u readonly -p your_password
mongo admin --host localhost --port 27017 -u special -p your_password
That’s it. Depending on your requirements, you need to set up a finer access control than these examples. For further details, you can check out the documentations below.