It took me a while to figure out how to use authentication with Mongo DB, so I thought I would write a blog about it. This is useful for example, when using text search, your user needs to have admin rights for the database. It is also good practice whenever your database is hosted on a public server to use authentication, to stop just anyone being able to access your data.
Setting up the config file
The first thing to realise is that when you install MongoDB as a windows service you can install it with a config file option. This is the place where you can specify that the service should run with or without authentication.
You need to open the mongod.cfg file and add the following line: "auth = true"
Then when you install MongoDB as a windows service you can pass in the path to the config file as a parameter. For Example: “D:\mongodb\bin\mongod.exe --config D:\mongodb\mongod.cfg –install”
But first you will need to start the service with authentication turned off in order to create an admin login that you can use. So you will need to open up the config again and set “auth = false”. It took me a while to realise this, but every time you start the service, it checks the config file that you specified when you installed the service.
Then you can start the service now that auth is deactivated. Use the command “net start MongoDB”
Creating a user
So then you need to access the mongo shell. Use the command "D:\mongodb\bin\mongo.exe" (or whatever path your mongo.exe is under). Then it is important to switch to the admin database, there will always be an admin database, a user with a login for this admin database has access to all other databases. To switch to the admin database use the command “use admin”. Then you need to create a user for this database. Use the command “db.addUser(‘username’,’password’)”. Then if you want to check that the user was successfully created and has access to the admin database you can use the auth command: “db.auth(‘username’,’password’)” This should return a 1 if the authentication is successful.
Once you have created the login, then you need to restart the service with authentication turned on. So open up a new command prompt and type in “net stop MongoDB” to stop the service. Then reopen the mongod.cfg file and set “auth = true”. Then go back to the command prompt and restart the service with the command “net start MongoDB”. Now you have MongoDB running as a service with authentication.
Changing the connection string
In order to connect to the MongoDB now, you will need to add the username and password to your connection string:
<add name="MongoDB" connectionString="mongodb://’Username’:’Password’@optweb01/ />
Now your application should be able to connect to the MongoDB with admin rights.