使用Shell和Java驱动程序的MongoDB身份验证配置示例

Authentication enables user to verify identity before connecting to the database. At first, a user with admin privileges should be created and then additional users can be added.

身份验证使用户可以在连接到数据库之前验证身份。 首先,应创建具有管理员权限的用户,然后可以添加其他用户。

Let’s now create a user having admin privileges

现在让我们创建一个具有管理员权限的用户

  1. Start the MongoDB server without authentication (using mongod in command line)

    在不进行身份验证的情况下启动MongoDB服务器(在命令行中使用mongod)
  2. Create the user with admin privilege as specified below
    >use admin
    switched to db admin
    >db.createUser(
      {
        user: "Adam",
        pwd: "admin",
        roles:
        [
          {
            role: "userAdminAnyDatabase",
            db: "admin"
          }
        ]
      }
    )
    Successfully added user: {
    	"user" : "Adam",
    	"roles" : [
    		{
    			"role" : "userAdminAnyDatabase",
    			"db" : "admin"
    		}
    	]
    }
    >

    The createUser command creates a user “Adam” authenticated by the pwd field with the role being an admin role userAdminAnyDatabase in the database “admin“.

    createUser命令创建一个由pwd字段认证的用户“ Adam”,该角色是数据库admin中的管理员角色userAdminAnyDatabase

  3. Specify the authorization –auth in the mongodb service file and restart the mongodb service with authentication.

    在mongodb服务文件中指定授权–auth ,然后使用身份验证重新启动mongodb服务。
  4. Login to the mongo shell with admin user credentials as;
    mongo -u  Adam -p admin --authenticationDatabase admin

    Let’s verify the privileges for the user we just created as

    The runCommand accepts the usersInfo fields that holds the user name and showprivileges is set to true. This displays the privleges granted to the user “Adam”. The above command list quite a lot of data pertaining to the privileges of the user.

    mongo -u  Adam -p admin --authenticationDatabase admin

    让我们验证刚刚创建的用户的特权

    runCommand接受包含用户名的usersInfo字段,并将showprivileges设置为true。 这将显示授予用户“ Adam”的特权。 上面的命令列出了很多与用户特权有关的数据。

创建用户时分配角色 (Assigning Roles while creating user)

Let’s create the new user with the CreateUser command and associate a role to it.

让我们使用CreateUser命令创建新用户,并将角色与其关联。

>use admin
switched to db admin
>db.createUser(
    {
      user: "Jack",
      pwd: "jack",
      roles: [
         { role: "read", db: "test" },
         { role: "read", db: "car" },
         ]
    }
)
Successfully added user: {
	"user" : "Jack",
	"roles" : [
		{
			"role" : "read",
			"db" : "test"
		},
		{
			"role" : "read",
			"db" : "car"
		}
	]
}
>

The user “Jack” is added with the role “read” on databases car and test. If we try to insert documents we get an error since we have specified a read only role.

在数据库car和test上为用户“ Jack”添加了“读取”角色。 如果我们尝试插入文档,则由于指定了只读角色,因此会出现错误。

WriteResult({
	"writeError" : {
		"code" : 13,
		"errmsg" : "not authorized on test to execute command { insert: \"products\", documents: [ { _id: ObjectId('5479b0dc9d9c8808eadff8b7'), item: \"card\", qty: 15.0 } ], ordered: true }"
	}
})

创建角色 (Creating Role)

The createRole command is used to create a new role to the user.

createRole命令用于为用户创建一个新角色。

>use admin
switched to db admin
>db.createRole(
   {
     role: "userRole",
     privileges: [
       { resource: { cluster: true }, actions: [ "killop", "inprog" ] },
       { resource: { db: "", collection: "" }, actions: [ "killCursors" ] }
     ],
     roles: []
   }
)
{
	"role" : "userRole",
	"privileges" : [
		{
			"resource" : {
				"cluster" : true
			},
			"actions" : [
				"killop",
				"inprog"
			]
		},
		{
			"resource" : {
				"db" : "",
				"collection" : ""
			},
			"actions" : [
				"killCursors"
			]
		}
	],
	"roles" : [ ]
}
>

The “userRole” has the permission to kill any operation as specified in the create role command. inprog is a system level role that shows the active or pending operations. There are numerous built in roles like read, readwrite, dbadmin etc. each of which are associated with actions like killop, inprog etc.

“ userRole”有权终止create role命令中指定的任何操作。 inprog是系统级别的角色,它显示活动或挂起的操作。 有许多内置角色,例如读取,读写,dbadmin等。每个角色都与诸如killop,inprog等操作关联。

授予角色 (Granting a Role)

Grant a role to the user with grantRolesToUser method as;

使用grantRolesToUser方法将角色授予用户;

>use admin
switched to db admin
>db.grantRolesToUser(
  "Jack",
  [
    {
      role: "readWrite", db: "admin"
    },
    {
      role: "readAnyDatabase", db:"admin"
    }
  ]
)

识别用户角色 (Identify user role)

The usersInfo command or db.getUser() method is used to fetch user information.

usersInfo命令或db.getUser()方法用于获取用户信息。

>db.getUser("Jack")
{
	"_id" : "admin.Jack",
	"user" : "Jack",
	"db" : "admin",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "admin"
		},
		{
			"role" : "read",
			"db" : "car"
		},
		{
			"role" : "readAnyDatabase",
			"db" : "admin"
		},
		{
			"role" : "read",
			"db" : "test"
		}
	]
}

As you can see we have now provided readwrite role to jack user.

如您所见,我们现在向jack用户提供了readwrite角色。

撤销角色 (Revoking a Role)

If you want to revoke any of the roles, we can do it as below

如果您想撤销任何角色,我们可以按照以下步骤进行操作

>db.revokeRolesFromUser(
    "Jack",
   [
    { role: "readWrite", db: "admin" }
    ]
 )

As you can see below, readwrite is no more associated with this user.

如下所示,该用户不再具有读写权限。

db.getUser("Jack")
{
	"_id" : "admin.Jack",
	"user" : "Jack",
	"db" : "admin",
	"roles" : [
		{
			"role" : "read",
			"db" : "car"
		},
		{
			"role" : "readAnyDatabase",
			"db" : "admin"
		},
		{
			"role" : "read",
			"db" : "test"
		}
	]
}

修改用户密码 (Change User Password)

To change the password use changeUserPassword method as;

要更改密码,请使用changeUserPassword方法:

db.changeUserPassword("Jack", "rem123")

Now if we try to login with the old password an exception “login failed exception” is thrown.

现在,如果我们尝试使用旧密码登录,则会引发异常“登录失败异常”。

MongoDB Java身份验证程序 (MongoDB Java Program for Authentication)

Below is a simple program showing how to pass MongoDB database user/password details programatically. Note that I am using mongo-java-driver version 2.13.0-rc0, if you are on some other version then there might be some changes required in the way MongoCredentials are created.

下面是一个简单的程序,显示了如何以编程方式传递MongoDB数据库用户/密码详细信息。 请注意,我使用的是mongo-java-driver版本2.13.0-rc0,如果您使用的是其他版本,则创建MongoCredentials的方式可能需要进行一些更改。

package com.journaldev.mongodb;

import java.net.UnknownHostException;
import java.util.Arrays;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

public class MongoDBAuthenticationExample {

	public static void main(String[] args) throws UnknownHostException {

		// create user with username,password and specify the database name
		MongoCredential credential = MongoCredential.createCredential(
				"journaldev", "admin", "journaldev".toCharArray());

		// create an instance of mongoclient
		MongoClient mongoClient = new MongoClient(new ServerAddress(),
				Arrays.asList(credential));

		// get the test db useyour own here
		DB db = mongoClient.getDB("admin");

		// get the car collection
		DBCollection coll = db.getCollection("car");

		// create new car object to insert
		BasicDBObject b1 = new BasicDBObject("name", "Qualis");

		// shows user privileges
		DBObject d1 = new BasicDBObject("usersInfo", new BasicDBObject("user",
				"journaldev").append("db", "admin")).append("showPrivileges", true);

		// insert new document
		coll.insert(b1);

		// execute the command for privileges
		System.out.println(db.command(d1));

		// cursor to store the result
		DBCursor c = coll.find();
		// iterate through cursor
		try {
			while (c.hasNext()) {

				System.out.println(c.next());
			}
		} finally {
			c.close();
		}

	}

}

Above program produces following output.

上面的程序产生以下输出。

{ "serverUsed" : "127.0.0.1:27017" , "users" : [ { "_id" : "admin.journaldev" , "user" : "journaldev" , "db" : "admin" , "roles" : [ { "role" : "readWrite" , "db" : "admin"} , { "role" : "readAnyDatabase" , "db" : "admin"} , { "role" : "userAdminAnyDatabase" , "db" : "admin"}] , "inheritedRoles" : [ { "role" : "readWrite" , "db" : "admin"} , { "role" : "readAnyDatabase" , "db" : "admin"} , { "role" : "userAdminAnyDatabase" , "db" : "admin"}] , "inheritedPrivileges" : [ { "resource" : { "db" : "admin" , "collection" : ""} , "actions" : [ "collStats" , "convertToCapped" , "createCollection" , "createIndex" , "dbHash" , "dbStats" , "dropCollection" , "dropIndex" , "emptycapped" , "find" , "insert" , "killCursors" , "planCacheRead" , "remove" , "renameCollectionSameDB" , "update"]} , { "resource" : { "db" : "admin" , "collection" : "system.indexes"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "admin" , "collection" : "system.js"} , "actions" : [ "collStats" , "convertToCapped" , "createCollection" , "createIndex" , "dbHash" , "dbStats" , "dropCollection" , "dropIndex" , "emptycapped" , "find" , "insert" , "killCursors" , "planCacheRead" , "remove" , "renameCollectionSameDB" , "update"]} , { "resource" : { "db" : "admin" , "collection" : "system.namespaces"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "" , "collection" : ""} , "actions" : [ "changeCustomData" , "changePassword" , "collStats" , "createRole" , "createUser" , "dbHash" , "dbStats" , "dropRole" , "dropUser" , "find" , "grantRole" , "killCursors" , "planCacheRead" , "revokeRole" , "viewRole" , "viewUser"]} , { "resource" : { "cluster" : true} , "actions" : [ "authSchemaUpgrade" , "invalidateUserCache" , "listDatabases"]} , { "resource" : { "db" : "" , "collection" : "system.indexes"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "" , "collection" : "system.js"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "" , "collection" : "system.namespaces"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "" , "collection" : "system.users"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "admin" , "collection" : "system.users"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "admin" , "collection" : "system.roles"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "admin" , "collection" : "system.version"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "admin" , "collection" : "system.new_users"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]} , { "resource" : { "db" : "admin" , "collection" : "system.backup_users"} , "actions" : [ "collStats" , "dbHash" , "dbStats" , "find" , "killCursors" , "planCacheRead"]}]}] , "ok" : 1.0}
{ "_id" : { "$oid" : "5493dffbc26bbdbbe1ba044f"} , "name" : "Toyota"}
{ "_id" : { "$oid" : "5493e21f036442627943d846"} , "name" : "Qualis"}

That’s all for authentication in MongoDB using simple user/password mechanism.

在MongoDB中使用简单的用户/密码机制进行身份验证就可以了。

翻译自: https://www.journaldev.com/6328/mongodb-authentication-configuration-example-using-shell-and-java-driver

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值