Unauthorized dropDatabase in MangoDB

Normally when you want to drop a database in MongoDB, you just need these command.

> use mydatabase;
switched to db mydatabase
> db.dropDatabase();

Error message with Unauthorized

But when you see this error, it mean you are not authorized and not enough level access to run the command. Drop database in MongoDB, you need MongoDB root role.

{
	"ok" : 0,
	"errmsg" : "not authorized on mydatabase to execute command { dropDatabase: 1.0, writeConcern: { w: \"majority\", wtimeout: 600000.0 }, lsid: { id: UUID(\"a197624a-eb84-400d-866f-30030cc5c317\") }, $db: \"mydatabase\" }",
	"code" : 13,
	"codeName" : "Unauthorized"
}

Solution to Add root role access.

> use admin;
switched to db admin
> db.grantRolesToUser("admin", ["root"]);
> show users;
{
	"_id" : "admin.admin",
	"userId" : UUID("6d653372-4975-4bf9-86e3-63ab9a8ce79f"),
	"user" : "admin",
	"db" : "admin",
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		},
		{
			"role" : "readWriteAnyDatabase",
			"db" : "admin"
		},
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
> use mydatabase;
switched to db mydatabase
> db.dropDatabase();
{ "dropped" : "mydatabase", "ok" : 1 }

Revoke back the root Role

For safety reason, it is userAdminAnyDatabase and readWriteAnyDatabase roles are enough for normal usage, and should revoke the root roles.

> use admin;
> db.revokeRolesFromUser("admin", ["root"]);
> show users;
{
	"_id" : "admin",
	"userId" : UUID("6d653372-4975-4bf9-86e3-63ab9a8ce79f"),
	"user" : "admin",
	"db" : "admin",
	"roles" : [
		{
			"role" : "readWriteAnyDatabase",
			"db" : "admin"
		},
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

Tags:

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version