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 nameMongoCredential credential = MongoCredential.createCredential("journaldev", "admin", "journaldev".toCharArray());// create an instance of mongoclientMongoClient mongoClient = new MongoClient(new ServerAddress(),Arrays.asList(credential));// get the test db useyour own hereDB db = mongoClient.getDB("admin");// get the car collectionDBCollection coll = db.getCollection("car");// create new car object to insertBasicDBObject b1 = new BasicDBObject("name", "Qualis");// shows user privilegesDBObject d1 = new BasicDBObject("usersInfo", new BasicDBObject("user","journaldev").append("db", "admin")).append("showPrivileges", true);// insert new documentcoll.insert(b1);// execute the command for privilegesSystem.out.println(db.command(d1));// cursor to store the resultDBCursor c = coll.find();// iterate through cursortry {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

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

  1. 使用Mongo Shell和Java驱动程序的MongoDB Map Reduce示例

    Map Reduce is a data processing technique that condenses large volumes of data into aggregated resul ...

  2. 使用Mongo Shell和Java驱动程序删除MongoDB的示例

    MongoDB remove method removes a single document or all the documents present in the collection or th ...

  3. mongodb身份验证_MongoDB身份验证

    mongodb身份验证 我最近更新了Mongometer ,使其更加灵活. 发布新版本后不久,其中一位用户通过在帖子中发表评论来反馈问题. 我启动了我的机器,打开了我的IDE,发现了问题,并在半小时内 ...

  4. MongoDB身份验证

    我最近更新了Mongometer ,使其更加灵活. 发布新版本后不久,其中一位用户通过在帖子中发表评论来反馈问题. 我启动了我的机器,打开了我的IDE,发现了问题,并在半小时内将修复程序推送到了git ...

  5. 用java写一个判断身份验证是否过期

    要用 Java 写一个判断身份验证是否过期,可以使用 Java 的日期和时间 API,例如:java.time 包中的 Instant 类. 首先,需要存储身份验证的创建时间,并在每次请求时与当前时间 ...

  6. aws rds监控慢sql_AWS RDS SQL Server中的初始Windows身份验证配置

    aws rds监控慢sql In this article, we will be exploring the process of enabling Windows authentication i ...

  7. aws rds监控慢sql_AWS RDS SQL Server中的高级Windows身份验证配置

    aws rds监控慢sql This article will cover advanced configurations for Windows Authentication in AWS RDS ...

  8. Java学习笔记_身份验证机制

    身份验证机制(authentication):确定一个用户具有自己声称的那个身份 应用程序关心用户是否通过了验证而不关心是通过何种方式进行的验证??? 授权(访问控制:authorization):★ ...

  9. 使用JAVA进行ad域身份验证常用属性详解

    一些变态的公司经常对开发者提出一些变态的问题.比如在oa系统中,要求登录验证必须使用ad域进行登录.还有的如登录crm系统必须使用公司的阿里云邮箱账号进行身份验证等等. 作为程序员我们只能按照客户的需 ...

最新文章

  1. 【blender教程】从头到尾全流程创建一辆吉普车
  2. html用户注册信息,首页-用户注册-填写注册信息
  3. 理解学习this指向问题
  4. [置顶] ActivityGroup自我堆栈管理(复用现有activity)
  5. android sdk 源码解析
  6. Docker创建虚机和swarm
  7. 一款超强的手机屏幕投影工具
  8. Redux 并不慢,只是你使用姿势不对 —— 一份优化指南
  9. java循环队列_Java 循环队列的实现
  10. Docker安装ActiveMQ(docker-compose.yml)
  11. 翻译:iOS Swift单元测试 从入门到精通 Unit Test和UI测试 UITest
  12. f-stack nginx 单进程模式BSD网络初始化流程
  13. Windows系统-删除指定服务!
  14. 怎么讲计算机屏幕录制,电脑如何录制屏幕
  15. Luogu P1725 琪露诺
  16. 百度智能云智慧监管平台落地宁波,物联网加持赋能安全生产
  17. Android SDK官方下载地址及在线SDK网址
  18. ubuntu 16.04 安装anaconda tensorflow opencv keras openslide-python pycharm
  19. Android 大众点评的接入
  20. 检查SSD固态硬盘的使用量和寿命

热门文章

  1. 《程序设计实践》读书笔记第五至六章
  2. 四级过了,我却高兴不起来!
  3. 在 Linux 上部署 Django 应用,nginx+gunicorn+supervisor
  4. [转载] 【python】内置函数 slice()
  5. [转载] Python连接MySQL、Mongodb、SQLite
  6. full stack front end
  7. PCL Lesson 4:直通滤波+多视图可视化
  8. 用计算机考试有老师引导,河北省教师计算机考试评价题及答案
  9. php smarty ci,CI整合Smarty,cismarty_PHP教程
  10. 浅谈java封装xml报文,XML报文转JAVA对象-JAVA对象转XML报文