User that be able to view a specific collection only - mongodb

is that possible to create a user in MongoDB that is only able to view a specific collection with reading permission only, no other privileges are granted?

Yes it is possible, You'll need to create a customized role. Then assign it to a new User in the DB.
Custom Role Command:
use testdb
db.createRole(
{
createRole: "readTestColOnly",
privileges: [
{ resource: { db: "testdb", collection: "testcollection" },
actions: [ "find" ] }
],
roles: []
})
New User Command:
use testdb
db.runCommand({
"createUser" : "testuser",
"customData" : {
},
"roles" : [
{
"role" : "readTestColOnly",
"db" : "testdb"
}
]
});
Hope This helps.

Related

MongoDB User Is Not Authorized To

In Mongo, I've created a database and created a user specifically for that database. When I type "show users" I get this:
rs0:PRIMARY> show users;
{
"_id" : "sampleuser.sampleuser",
"user" : "sampleuser",
"db" : "sampledb",
"roles" : [
{
"role" : "readWrite",
"db" : "sampledb"
},
{
"role" : "dbAdmin",
"db" : "sampledb"
}
]
}
But when I try to execute a command with that user, I get the following:
not authorized on sampledb to execute command { find: "social_posts", filter: { customer_id: "123", 0: { posted: { $ne: 1 } } } }
What permissions are setup wrong?
You have to use db.auth() to authenticate to the database before executing any query.
From db.auth() doc
db.auth()
Allows a user to authenticate to the database from within the shell.
The db.auth() method can accept:
the username and password.
db.auth( <username>, <password> )
a user document that contains the username and password, and optionally, the authentication mechanism and a digest password flag.
db.auth( {
user: <username>,
pwd: <password>,
mechanism: <authentication mechanism>,
digestPassword: <boolean>
}
Returns: db.auth() returns 0 when authentication is not successful, and 1 when the operation is successful.

mongodb: how to set correctly roles and privileges?

I added an 'admin' user in the admin db, with roles on admin db and another db :
[admin] user: yves>db.auth("isabelle", "abc123")
1
[admin] user: isabelle>db.getUser("isabelle")
{
"_id" : "admin.isabelle",
"user" : "isabelle",
"db" : "admin",
"roles" : [
{
"role" : "userAdmin",
"db" : "admin"
},
{
"role" : "dbOwner",
"db" : "cockpit"
}
]
}
I am testing that this user cannot admin the 'test' database ( updating a tester user email )
[admin] user: isabelle>use test
switched to db test
[test] user: isabelle>db.updateUser(
... "myTester",
... {
... customData: {email: "mytester#example.com"}
... }
... )
As 'isabelle' has no roles on 'test' db , she should not be allowed to update any user on this db ... (?)
but it is ...
[test] user: isabelle>db.getUser("myTester")
{
"_id" : "test.myTester",
"user" : "myTester",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "reporting"
}
],
"customData" : {
"email" : "mytester#example.com"
}
}
what am I missing ?
do the isabelle' role 'userAdmin' on 'admin' db allow it ?
I tried to remove it, but it deosn(t change anything ...
I also tried to move isabelle in the cockpit database, with dbOwner role, it doesn't change anything... isabelle is still able to update myTester user in the test database...
how can I restrict isabelle to admin only the 'cockpit' db ( managing users and roles for this db ..?
thanks for enlightment ...
Add to your mongod.conf
security:
authorization: enabled
Also check this mongodb link.

Create mongo user with right to read local database

I would like to create a mongo user who can read local database. I try to use command on local database:
db.createUser(
{ user: "readonlyuser", pwd: "loh8Ephi",
roles: [ { role: "read", db: "local" } ]
})
But - it doesn't work. I receive:
connecting to: local
2015-12-21T14:08:07.904+0100 Error: couldn't add user: Cannot create users in the local database at src/mongo/shell/db.js:1054
I've tried to create that user against admin database:
> use admin
switched to db admin
> db.createUser(
... { user: "readonlyuser", pwd: "loh8Ephi", roles: [ { role: "read", db: "local" } ] })
Successfully added user: {
"user" : "readonlyuser",
"roles" : [
{
"role" : "read",
"db" : "local"
}
]
And now i try to connect:
undefine#machine:~$ mongo -u readonlyuser -p loh8Ephi local
MongoDB shell version: 2.6.11
connecting to: local
2015-12-21T15:35:19.190+0100 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1292
exception: login failed
How to create readonly user who have access only to local database?
According the documentation, you cannot create users on the local database. Instead you can run your createUser query against the admin database:
use admin
db.createUser(
{ user: "readonlyuser", pwd: "loh8Ephi",
roles: [ { role: "read", db: "local" } ]
})
Please note that you will have to authenticate against the admin database when connecting.
I would do it like below
use admin
db.getSiblingDB("local").runCommand( { "createUser" : "mongoread", "pwd": "read0nly", "customData" : { "description": "mongo readonly user" }, "roles" : [ {"role" : "read","db" : "local"}] },{ w: "majority" , wtimeout: 5000 } );

MongoDB "root" user

Is there a super UNIX like "root" user for MongoDB? I've been looking at http://docs.mongodb.org/manual/reference/user-privileges/ and have tried many combinations, but they all seem to lack in an area or another. Surely there is a role that is above all the ones listed there.
The best superuser role would be the root.The Syntax is:
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
})
For more details look at built-in roles.
While out of the box, MongoDb has no authentication, you can create the equivalent of a root/superuser by using the "any" roles to a specific user to the admin database.
Something like this:
use admin
db.addUser( { user: "<username>",
pwd: "<password>",
roles: [ "userAdminAnyDatabase",
"dbAdminAnyDatabase",
"readWriteAnyDatabase"
] } )
Update for 2.6+
While there is a new root user in 2.6, you may find that it doesn't meet your needs, as it still has a few limitations:
Provides access to the operations and all the resources of the
readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase and
clusterAdmin roles combined.
root does not include any access to collections that begin with the
system. prefix.
Update for 3.0+
Use db.createUser as db.addUser was removed.
Update for 3.0.7+
root no longer has the limitations stated above.
The root has the validate privilege action on system. collections.
Previously, root does not include any access to collections that begin
with the system. prefix other than system.indexes and
system.namespaces.
Mongodb user management:
roles list:
read
readWrite
dbAdmin
userAdmin
clusterAdmin
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase
create user:
db.createUser(user, writeConcern)
db.createUser({ user: "user",
pwd: "pass",
roles: [
{ role: "read", db: "database" }
]
})
update user:
db.updateUser("user",{
roles: [
{ role: "readWrite", db: "database" }
]
})
drop user:
db.removeUser("user")
or
db.dropUser("user")
view users:
db.getUsers();
more information: https://docs.mongodb.com/manual/reference/security/#read
There is a Superuser Roles: root, which is a Built-In Roles, may meet your need.
I noticed a lot of these answers, use this command:
use admin
which switches to the admin database. At least in Mongo v4.0.6, creating a user in the context of the admin database will create a user with "_id" : "admin.administrator":
> use admin
> db.getUsers()
[ ]
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' } ] })
> db.getUsers()
[
{
"_id" : "admin.administrator",
"user" : "administrator",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
]
I emphasize "admin.administrator", for I have a Mongoid (mongodb ruby adapter) application with a different database than admin and I use the URI to reference the database in my mongoid.yml configuration:
development:
clients:
default:
uri: <%= ENV['MONGODB_URI'] %>
options:
connect_timeout: 15
retry_writes: false
This references the following environment variable:
export MONGODB_URI='mongodb://administrator:changeme#127.0.0.1/mysite_development?retryWrites=true&w=majority'
Notice the database is mysite_development, not admin. When I try to run the application, I get an error "User administrator (mechanism: scram256) is not authorized to access mysite_development".
So I return to the Mongo shell delete the user, switch to the specified database and recreate the user:
$ mongo
> db.dropUser('administrator')
> db.getUsers()
[]
> use mysite_development
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' } ] })
> db.getUsers()
[
{
"_id" : "mysite_development.administrator",
"user" : "administrator",
"db" : "mysite_development",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
]
Notice that the _id and db changed to reference the specific database my application depends on:
"_id" : "mysite_development.administrator",
"db" : "mysite_development",
After making this change, the error went away and I was able to connect to MongoDB fine inside my application.
Extra Notes:
In my example above, I deleted the user and recreated the user in the right database context. Had you already created the user in the right database context but given it the wrong roles, you could assign a mongodb built-in role to the user:
db.grantRolesToUser('administrator', [{ role: 'root', db: 'admin' }])
There is also a db.updateUser command, albiet typically used to update the user password.
It is common practice to have a single db that is used just for the authentication data for a whole system.
On the connection uri, as well as specifying the db that you are connecting to use, you can also specify the db to authenticate against.
"mongodb://usreName:passwordthatsN0tEasy2Gue55#mongodb.myDmoain.com:27017/enduserdb?authSource=myAuthdb"
That way you create all your user credentions AND roles in that single auth db.
If you want a be all and end all super user on a db then, you just givem the role of "root#thedbinquestion"
for example...
use admin
db.runCommand({
"updateUser" : "anAdminUser",
"customData" : {
},
"roles" : [
{
"role" : "root",
"db" : "thedbinquestion"
} ] });
now you can change your built-in role to atlas admin in the console;
this fixed my issue.
"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted

How do you change MongoDB user permissions?

For instance, if I have this user:
> db.system.users.find()
{ "user" : "testAdmin", "pwd" : "[some hash]", "roles" : [ "clusterAdmin" ], "otherDBRoles" : { "TestDB" : [ "readWrite" ] } }
And I want to give that user the dbAdmin permissions on the TestDB database, I can remove the user record then add it back with the new permissions:
> db.system.users.remove({"user":"testAdmin"})
> db.addUser( { user: "testAdmin",
pwd: "[whatever]",
roles: [ "clusterAdmin" ],
otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] } } )
But that seems hacky and error-prone.
And I can update the table record itself:
> db.system.users.update({"user":"testAdmin"}, {$set:{ otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] }}})
But I'm not sure if that really creates the correct permissions - it looks fine but it may be subtly wrong.
Is there a better way to do this?
If you want to just update Role of User. You can do in the following way
db.updateUser( "userName",
{
roles : [
{ role : "dbAdmin", db : "dbName" },
{ role : "readWrite", db : "dbName" }
]
}
)
Note:- This will override only roles for that user.
See array update operators.
> db.users.findOne()
{
"_id" : ObjectId("51e3e2e16a847147f7ccdf7d"),
"user" : "testAdmin",
"pwd" : "[some hash]",
"roles" : [
"clusterAdmin"
],
"otherDBRoles" : {
"TestDB" : [
"readWrite"
]
}
}
> db.users.update({"user" : "testAdmin"}, {$addToSet: {'otherDBRoles.TestDB': 'dbAdmin'}}, false, false)
> db.users.findOne()
{
"_id" : ObjectId("51e3e2e16a847147f7ccdf7d"),
"user" : "testAdmin"
"pwd" : "[some hash]",
"roles" : [
"clusterAdmin"
],
"otherDBRoles" : {
"TestDB" : [
"readWrite",
"dbAdmin"
]
},
}
Update:
MongoDB checks permission on every access. If you see operator db.changeUserPassword:
> db.changeUserPassword
function (username, password) {
var hashedPassword = _hashPassword(username, password);
db.system.users.update({user : username, userSource : null}, {$set : {pwd : hashedPassword}});
var err = db.getLastError();
if (err) {
throw "Changing password failed: " + err;
}
}
You will see — operator changes user's document.
See also system.users Privilege Documents and Delegated Credentials for MongoDB Authentication