Mongodb – Why do databases in mongodb have roles

access-controlauthenticationmongodbrole

I have read about mongodb role based access control and I have understood it to a large extent. I was going through this tutorial and when you run show roles on the mongo shell it returns a different set of roles for a given database.

  1. Why does each database have its own roles? Yet we allocate roles to users. Does this mean that if you create a user in that db they can only be allocated roles present in that database?
  2. What is importance of having an authentication database as opposed to saving all uses in a single database, for example like admin? Is there any advantage of having different authentication databases?

Best Answer

I don't think it makes any sense to define users and roles anywhere else than in admin database. If you define them somewhere else then likely your user/role management get unmanageable.

From db.createRole():

Except for roles created in the admin database, a role can only include privileges that apply to its database and can only inherit from other roles in its database.

A role created in the admin database can include privileges that apply to the admin database, other databases or to the cluster resource, and can inherit from roles in other databases as well as the admin database.

So, creating roles in "non-admin" database is much more limited. However, creating users and roles is usually an admin task and typically admins have full power anyway. Perhaps when you like to provide a MongoDB playground (e.g. https://mongoplayground.net/) then such limits could be useful.

Note, when you run a MongoDB Sharded Cluster then users and roles are commonly defined in the Config Server Replica Set. When you connect to a Shard directly then the shard contacts the Config Server in order to authenticate your connection. However, when your shard is disconnected from the cluster then it cannot contact the Config Server. For this you define a Shard Local User directly on the shards, see Create the shard-local user administrator. I think this is the only useful exception where users are not defined in common admin database.