Mongodb adding user access for authentication on remote server

By default if you install mongodb into your server, it doesn't automatically add a default user or enable authentication. However, you might wan to add in authentication on your Mongodb configuration once you have more than one database. Before you do anything, we first needs to add user into our collection.

Mongodb adding user access

In order to add a new user, we will just have to access our mongodb without password on the command line,

[[email protected] ~]# mongo
MongoDB shell version: 3.0.0
connecting to: test
Server has startup warnings:
2015-10-10T18:45:14.364+0800 I CONTROL [initandlisten]
2015-10-10T18:45:14.364+0800 I CONTROL [initandlisten] ** WARNING: You are running in OpenVZ which can cause issues on versions of RHEL older than RHEL6.
2015-10-10T18:45:14.364+0800 I CONTROL [initandlisten]

As you can see i did not have any password enable. Next, we want to add this user to mongodb and the collection access i want to give my user to is call 'storage', so i'm going to switch to storage directly.

> use storage
switched to db storage

In order to add a new user with read and write permission. All i have to do is to fire the below command.

take note that the 'role', the permission available are 'readWrite', 'read' and 'write'. And the 'db' is basically the database allowed for this particular added user. I have added read for shopping database and readWrite for storage for this particular 'user'.

Let's test this before we go to the next step

db.auth("user", "password")
>1

where 1 refer to valid and 0 refer to invalid. Now we will need to change our mongodb to an auth mode by going to /etc/mongod.conf

# for version below 3.0
# Turn on/off security. Off is currently the default
#noauth=true
#auth=true
# for version above 3.0 - YAML based
#security:
# authorization: enabled

look for this line and uncomment the it which will gives you the below configure file

# for version below 3.0
# Turn on/off security. Off is currently the default
#noauth=true
#auth=true
# for version above 3.0 - YAML based
security:
authorization: enabled