MongDB的用户认证管理



MongoDB 安装后默认不启用认证,也就是说在本地可以通过 mongo 命令不输入用户名密码, 直接登陆到数据库,下面介绍下启用 mongodb 用户认证

一、修改启动方式:

我是通过配置文件的方式来启动的,因此在mongo.conf文件中加入auth = true

[root@localhost mongodb]# cat mongo.conf

port = 27017
dbpath = /usr/local/mongodb/data
logpath = /usr/local/mongodb/logs/mongodb.log
logappend = true
auth = true
fork = true

然后启动数据库:

[root@localhost bin]# ./mongod --config ../mongo.conf
all output going to: /usr/local/mongodb/logs/mongodb.log
forked process: 24885
child process started successfully, parent exiting

启动成功后,用户登录就需要帐号和密码了。


二、用户登录:

登录的命令行格式如下:

./mongo [options] [db address] [file names (ending in .js)]

我们可以先登录,然后再认证,也可以直接认证登录

a) 直接认证登录

[root@localhost bin]# ./mongo admin -u admin -p 123456
MongoDB shell version: 2.2.3
connecting to: admin


b) 先登录,再认证

[root@localhost bin]# ./mongo
MongoDB shell version: 2.2.3
connecting to: test
> use admin
switched to db admin

> db.auth("admin","123456");
1


三、用户管理

MongoDB的用户分管理员用户和普通用户,管理员用户在admin库中创建,能访问所有数据库,普通用户在本数据库中创建,只能访问本数据库,

1.添加和修改用户

命令格式:db.addUser(username,password,readOnly);

Use this function to create new database users, by specifying a username and password as arguments
to the command. If you want to restrict the user to have only read-only privileges, supply a true third
argument; however, this defaults to false。

rameters:     
username (string) – Specifies a new username.
password (string) – Specifies the corresponding password.
readOnly (boolean) – Optional. Restrict a user to read-privileges only. Defaults to false.

举例:

a.添加一个管理员用户

> use admin
switched to db admin
> db.addUser("hysh","hysh");
{
        "user" : "hysh",
        "readOnly" : false,
        "pwd" : "e56cbca5fd83d8e0ab101b67d53e04ac",
        "_id" : ObjectId("55373d09bb0a9336dd8ad591")
}


b. 添加一个只读普通用户,如果添加一个可读写的用户,将参数true去掉即可。

> use test
switched to db test
> db.addUser("test","123456",true);
{
        "user" : "test",
        "readOnly" : true,
        "pwd" : "c8ef9e7ab00406e84cfa807ec082f59e",
        "_id" : ObjectId("55373dc8bb0a9336dd8ad592")
}

修改用户信息也是使用db.addUser()函数。可以修改密码和是否只读等。


2. 查询用户

如下,查出2个用户:admin和hysh

> db.system.users.find();
{ "_id" : ObjectId("553476c3644ec953555f3b16"), "user" : "admin", "readOnly" : false, "pwd" : "95ec4261124ba5951720b199908d892b" }
{ "_id" : ObjectId("55373d09bb0a9336dd8ad591"), "user" : "hysh", "readOnly" : false, "pwd" : "e56cbca5fd83d8e0ab101b67d53e04ac" }


3. 删除用户

命令格式:db.system.users.remove({user:username})
举例:

a. 删除用户名为hysh的用户

> db.system.users.remove({user:"hysh"});
> db.system.users.find();
{ "_id" : ObjectId("553476c3644ec953555f3b16"), "user" : "admin", "readOnly" : false, "pwd" : "95ec4261124ba5951720b199908d892b" }

 再查询只有一个用户了。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值