Enabling authentication on MongoDB

When I first installed MongoDB on my OpenBSD box I didn’t care about authentication, it was behind the firewall, purely for testing purposes. I first wanted to have some fun with it. But now I became curious and wanted to things right, so I enabled authentication.

In order to do so we first need to create an admin user:

$ mongo
> use admin
> db.createUser({ user: "admin", pwd: passwordPrompt(), roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] });
> exit

After that enable authentication in /etc/mongodb.conf by adding:

security:
  authorization: enabled

Restart mongod

$ doas rcctl restart mongod

After that you can connect to mongo with:

$ mongo --authenticationDatabase "admin" -u "admin" -p

And now we can create additional users for our applications:

> use my_db
> db.createUser({ "user": "db_user", "pwd": passwordPrompt(), roles: [{ role: "readWrite", db: "my_db" }]})

And lastly we implement the credentials in our php-project:

<?php

$mongo = new MongoDB\Driver\Manager("mongodb://db_user:password@localhost:27017/my_db");

And we are set to go!