如何在 mongodb 中为用户和管理员赋予不同的权限

how give different privilege for user and admin in mongodb

我正在使用 sails 和 MongoDB 创建一个应用程序。我需要三个级别的用户。

我想给每个用户不同的权限

那么如何为不同类型的用户使用不同的架构。并限制一个用户访问其他资源。

您所描述的仅在数据库级别是不可能实现的。

可以创建另一个对数据库具有不同 read/write 权限的用户。但是,无法创建仅有权查看与自己相关的数据的用户。您需要做的是在应用程序中执行身份验证,以查看用户是否有权查看所述数据。显然这是非常具体的实现,但它类似于执行 "is user ABC the owner of data XYZ? If yes, let them see it, if no, error".

的应用程序检查

I want to give the different privileges for each of user

  • Super admin can access whole DB.
  • Admin can access the data relate to that field
  • User can access the data related to the user.

您主要需要的是 document-level 访问控制,用户可以在其中根据特定字段中的值访问 document。不幸的是,从 3.0 版开始,还没有任何内置方法可以在 document/field 级别提供 access-control。 Mongo 的 ACL 去仅 Collection-level。

..So how to use different schema for the different type of user. and restrict one user to access the other resources.

由于上述原因,如果 'resource' 指的是 'document',这仅在数据库级别是不可能的。但是,您仍然可以设法在应用程序级别 (sailJS) 上实现类似的功能。 在数据库级别,您能做的最好的事情就是将用户文档移动到不同的 collection。您可以使用 createRole() 方法创建角色并指定其 权限

对于超级管理员:

db.createRole({ role: "SuperAdmin",
  privileges: [
    { resource: { db: "myCustomDB", collection: "" }, actions: [ "find", "update", "insert", "remove" ]}
  ],
  roles: []
})

超级管理员可以访问 myCustomDB 数据库中的所有 collection 并执行 findupdateinsertremove 操作

对于管理员:

db.createRole({ role: "Admin",
  privileges: [
    { resource: { db: "myCustomDB", collection: "AdminCollection" }, actions: [ "find", "update", "insert", "remove" ]},
    { resource: { db: "myCustomDB", collection: "" }, actions: [ "find"]}
  ],
  roles: []
})

管理员可以在自己的 collection 中访问所有文档并执行 CRUD 操作。但是,他们只能 read-only 访问数据库中的任何其他 collection。

对于用户:

db.createRole({ role: "User",
  privileges: [
    { resource: { db: "myCustomDB", collection: "UserCollection" }, actions: [ "find", "update", "insert", "remove" ]}
  ],
  roles: []
})

注意:如果您使用的是 2.4(或更低版本),则需要将用户 collection 移动到不同的数据库。 MongoDB 2.4(及以下)ACL 仅适用于 Database-Level。

假设您正在处理一个数据库名称 "records"

在mongoshell>>

//SuperADMIN
use admin
db.createUser(
 {
   user: "superuser",
   pwd: "12345678",
   roles: [ "root" ]
 }
 )


 //ADMIN
 use records
 db.createUser
 (
   {
     user: "recordsUserAdmin",
     pwd: "password",
     roles: [ { role: "userAdmin", db: "records" } ]
   }
 )





//Any User
use records
db.createUser(
 {
    user: "recordUser",
    pwd: "12345678",
    roles: [
       { role: "read", db: "records" },
       { role: "read", db: "user" },
       { role: "read", db: "sales" },
       { role: "readWrite", db: "accounts" }
    ]
  }
 )

更多信息:

Mongo tutorial create admin

Add user to mongo