MongoDB

MongoDB Create User and Assign Roles Example

Hello readers, these days in order to keep up the data integrity authentication and authorization of a user is important to use a database. In this tutorial, we will see how to set up more users in the MongoDB database and assign roles.

1. Introduction

If you have installed the MongoDB application on Windows or Ubuntu operating system and you wish to assign roles while creating users, then follow the below steps to give users a controlled access to your database. It’s very simple to manage users in MongoDB, but before moving further let’s take a look at MongoDB and its features.

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database contains collections which in turn contains documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.2 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes in order to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the numerous MongoDb occurrences
  • Replication: MongoDB can give high availability with the replica sets

2. MongoDB Create User and Assign Roles Example

In this MongoDB tutorial, we will learn how to enable the authentication and authorization of user’s where:

  • Authentication will force a user to show themselves and access the database through a name and password
  • Authorization will select what a user can do or not once he or she is connected to the database

2.1 Start MongoDB

The following command shows how to start a standalone mongod secure mode instance.

Syntax

> mongod --auth 

If the command is successfully executed, the following output will be shown.

Fig. 1: Start MongoDB instance
Fig. 1: Start MongoDB instance

2.2 Connect to the Mongo Instance

The following command shows how to connect a mongo shell to the MongoDB instance.

Syntax

> mongo

If the command is successfully executed, the following output will be shown.

Fig. 2: Connect to MongoDB
Fig. 2: Connect to MongoDB

2.3 Create a User with Administrator privileges

In this step, we will add the userAdminAnyDatabase role to the “admin” database. The following command shows how to create a user with the administrator privileges.

Syntax

> use admin

> db.createUser({ user: "dba", pwd: "manager", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })

This command creates an admin user authenticated by the “pwd” field. This user will have the administrator privileges on the “admin” database. If the command is successfully executed, the following output will be shown.

Fig. 3: Creating Administrator User
Fig. 3: Creating Administrator User

Once the user is successfully added, we will disconnect the mongo shell and reconnect again.

2.4 Connect with the Administrator user

To authenticate a user during the connection, we will start the mongo shell with the following command line options i.e.

  • -u <username>
  • -p <password>
  • –authenticationDatabase <database>

The following command shows how to authenticate a user during the connection.

Syntax

> mongo admin -u dba -p

If the command is successfully executed, the following output will be shown.

Fig. 4: Authenticating user in connection
Fig. 4: Authenticating user in connection

Do remember:

  • This user has the userAdminAnyDatabase role. With this role, developers can manage the users but cannot perform the read or write operations on the application databases or collections
  • If developers want to assign this user the power of reading and write any database, they can grant the readWriteAnyDatabase role to this user i.e.
    > db.grantRolesToUser("dba", [{ "role" : "readWriteAnyDatabase", "db" : "admin" }])
    

2.5 Create Application user

Now, we will create an application user that is responsible for the emp database. Authenticate the mongo shell via the administrator user and the following command shows how to create a user with the readWrite privileges.

Syntax

> use emp;

> db.createUser({ user: "app1", pwd: "app123", roles: [{ role: "readWrite", db: "emp" }] })

The “app” user will be able to read and write on the emp database and if the command is successfully executed, the following output will be shown.

Fig. 5: Application user
Fig. 5: Application user

2.5.1 Connect with Application user

Using the mongo shell developers can now connect and execute the different CRUD (i.e. Create, Read, Update, and Delete) operations. The following command shows how to execute the MongoDB queries.

Syntax

> mongo emp -u app1 -p

> db.jcg.insert([{"emp_id" : "101", "emp_name" : "Java Geek" }, {"emp_id" : "102", "emp_name" : "Harry Potter" }, {"emp_id" : "103", "emp_name" : "Lucifer Morningstar" }])

> db.jcg.find().pretty()

If the command is successfully executed, the following output will be shown.

Fig. 6: Application user activities
Fig. 6: Application user activities

Do note, that if developers try to query or modify another database with this user, they will receive the authorization exception.

2.6 Create Reporting user

Next, we will have a user that can only read data in all the databases. For this, developers just need to assign the readAnyDatabase role. Authenticate the mongo shell via the administrator user and the following command shows how to create a user with the readOnly privileges.

Syntax

> use admin

> db.createUser({ user: "rep", pwd: "rep123", roles: [{ role: "read", db: "emp" }] })

The “rep” user will be able to query all databases and if the command is successfully executed, the following output will be shown.

Fig. 7: Reporting user
Fig. 7: Reporting user

2.6.1 Connect with Reporting user

Using the mongo shell developers can now connect and execute the query data commands. The following command shows how to execute the MongoDB queries.

Syntax

> mongo emp -u rep -p

> show dbs

> use emp

> db.jcg.find().pretty()

If the command is successfully executed, the following output will be shown.

Fig. 8: Reporting user activities
Fig. 8: Reporting user activities

Do note, if developers try to insert, update or drop document with this user, they will receive the authorization exceptions.

That’s all for this post. Happy Learning!!

3. Conclusion

The main goal of this article is to give an introduction to MongoDB and how to enable the authentication and authorization of a user in MongoDB. Developers can download the sample application as an Eclipse project in the Downloads section.

4. Download the Eclipse Project

This was an example of user creation and assigning roles in MongoDB.

Download
You can download the full source code of this example here: MongoDbCreateUsers&AssignRolesEx

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button