I am writing a Golang-based tool which is used for managing users in MongoDB (version 7.0.x). I have a few questions around this whole process.
The user needs to be granted specific roles only to specific databases and the roles can be built-in as well custom. Something like
# config.yaml
user: myuser
permissions:
- db: mydb1
roles:
- read
- customRole1
- db: mydb2
roles:
- readWrite
- customRole2
My understanding of Mongodb user management is that a given user needs to be created within a database. Similarly, roles are also created within a database. Now, the user within that database is assigned roles. For eg, in below snippet, the db
field tell MongoDB retrieve the someCustomRole
from the customDb
(and it does NOT assign the role someCustomRole
to the user for accessing the customDb
).
///// via mongosh CLI
admin> db.createUser( {user:"myuser", pwd: "pass", roles: []});
{ ok: 1 }
admin> db.grantRolesToUser("myuser", [ "read", {role:"someCustomRole", db: "customDb" ])
{ ok: 1 }
////// via Golang driver
var result bson.D
roleBsonArray := bson.A{"read","readWrite"}
resp := client.Database("helloworld").RunCommand(context.Background(), bson.D{ {"grantRolesToUser", newuser}, {"roles", roleBsonArray}, }).Decode(&result)
fmt.Println("result: ", result)
fmt.Println("resp", resp )
Question1: Is my above understanding correct?
Question2: How would I create users in admin
database but then grant the same user specific roles to a specific list of databases? (as listed in config.yaml snippet above)
-
The documentation has a brief example where they create the user & roles within the required database, but if my user needs to have access to 5 databases, does it need to be created 5 times in each of the database?
-
How do i achieve this in Golang ?