20 December 2011

MongoDB and Authentication

By default, MongoDB allows access to the database without authentication. Adding a user with a username/password is easy, but authenticating might be a bit tricky since the official documentation does not say the command directly.
First, we add an admin account. Navigate to the MongoDB directory on your machine then start the database.
$ ./mongo
> use admin
> db.addUser(adminuser, adminpassword)
Switch to the database of your choice and add users to it.
> use foo
> db.addUser(myuser, userpassword)
This adds a user myuser that has read and write access to the database. If we want a user with read-only access, set the third parameter for addUser().
> db.addUser(guest, guestpassword, true)
You can check for users with access to a particular database like thus:
> db.system.users.find().pretty()
{
        "_id" : ObjectId("4ee9863d954eb7168e07089d"),
        "user" : "zarah",
        "readOnly" : false,
        "pwd" : "70581bfb1e32e2286df11fe119addc7a"
}
{
        "_id" : ObjectId("4ee98658954eb7168e07089e"),
        "user" : "guest",
        "readOnly" : true,
        "pwd" : "88558f1ece63fa0b528012b9840bd9de"
}

Now stop the MongoDB server and restart it with authentication enabled.
$ ./mongod --auth
> mongo foo -u myuser -p userpassword
where foo is the database that myuser has access to.
You can now read and write into database foo. Notice however that querying for databases would result to an error:
> show dbs
Mon Dec 19 17:21:20 uncaught exception: listDatabases failed:{ "errmsg" : "need to login", "ok" : 0 }

Exit MongoDB and login again, this time using the read-only account. If we try inserting a document, an error should appear:
> db.foo.insert({"title","MongoDB Authentication Test"})
unauthorized
The read-only account can query for collections and use find() and its variations. It can't, however, query for databases.

06 December 2011

Hello, it's me again.


To my two readers out there, hello! It's been a while since I posted here. I was transferred to another (non-Android) project and lost all my Internet privileges, hence the silence. I still can't believe almost every other site is blocked by the office firewall! Makes software development ten times harder. Ugh.

Anyway, as of the last three months, I have been working on backend development (J2EE). I don't know a lot about it, and the past months have been a great journey of learning. It is quite a shock being exposed all in one go to so many technologies and tools, I'm lucky my head didn't explode.

Happy as I am to learn new things, I am quite sad to leave Android development behind. I'm still hoping though that I would be given the chance to go back to it, and pick up where I left off. Hopefully the Android train won't be too far off by then.

In the meantime, I will be posting stuff that I've learned while working on J2EE, and hopefully somebody can learn from my mistakes. :)