What MongoDB user privileges do I need to add a user to a new/another mongo database?

后端 未结 2 1012
生来不讨喜
生来不讨喜 2020-12-23 15:33

I have enabled authentication in the MongoDB config file after adding one admin user with the following privileges: userAdmin and userAdminAnyDatabase

相关标签:
2条回答
  • 2020-12-23 15:44

    This is what worked for me for creating a user prod who connects to database prod assuming I had an admin user (called admin) already in the MongoDB:

    > mongo admin --username root --password <pwd>
    > use prod
    > db.createUser(
      {
        user: "prod",
        pwd: "<pwd>",
        roles: [ { role: "dbOwner", db: "prod" } ]
      }
    )
    > exit
    

    After this you can login with the new user prod like this:

    > mongo prod  --username prod --password <pwd>
    
    0 讨论(0)
  • 2020-12-23 15:46

    The mistake made was that I was using an userAdminAnyDatabase user that was NOT in the admin database (see this note). So there MUST be a database called admin on your server! As the documentation says for the "AnyDatabase" privileges:

    If you add any of these roles to a user privilege document outside of the admin database, the privilege will have no effect.

    So you must:

    • add a userAdminAnyDatabase to the admin db

      $ mongo admin
      > db.createUser({ user: "myadmin", pwd: "1234", roles: ["userAdminAnyDatabase"] })
      
    • turn on authentication

      auth = true
      setParameter = enableLocalhostAuthBypass=0
      
    • connect using the new myadmin user to any database you want and add further users:

      $ mongo another -u myadmin -p 1234
      > db.createUser({ user: "user", pwd: "1234", roles: ["readWrite"] })
      

      or

      > use another
      > db.createUser({ user: "user", pwd: "1234", roles: ["readWrite"] })
      
    0 讨论(0)
提交回复
热议问题