Search code examples
mongodbdatabase-connectioncompass

MongoDB authentication restriction for database


I have a database called flowers in which I have the collection named flower. When I first created it in MongoDB, I had no authentication set to it (I would just connect to it using the default port:27017 and localhost).

Then I wanted to restrict the access to this database, in order to be accessed only with a set of username & password. First, I created an admin in the admin database:

> use admin
switched to db admin
> db.createUser(
...   {
...     user: "myUserAdmin",
...     pwd: "abc123",
...     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
...   }
... )
Successfully added user: {
        "user" : "myUserAdmin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
> show users
{
        "_id" : "admin.myUserAdmin",
        "user" : "myUserAdmin",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}

Then I exited mongo, I restarted the service. Then I created a user for my database:

> use flowers
switched to db flowers
> db.createUser(
...   {
...     user: "adminfl",
...     pwd: "flower1",
...     roles: [ "dbOwner", "readWrite"]
...   }
... )
Successfully added user: { "user" : "adminfl", "roles" : [ "dbOwner", "readWrite" ] }

After this I exited mongo once again, restarted the service.... from Compass I tried to connect to database flowers using the username and password and specify the authentication database: flowers. Everything went well to this point.

My problem is: when I connect to mongo using the authentication I can see all the databases, and when I connect without authentication, I have the same result.

How can I make my database flowers visible only when I connect with a username & password?

Update: This is my mongod.cfg:

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: C:\Program Files\MongoDB\Server\4.0\data
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path:  C:\Program Files\MongoDB\Server\4.0\log\mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1


#processManagement:

#security:

#operationProfiling:


#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

Solution

  • Try adding below line if not added in your mongod.conf =>

    security:
      authorization: enabled
    

    Then restart mongodb and you are good to go.