mongodb 用户权限设置

mongodb默认链接是不需要用户名、密码的,直接IP、端口号就可以连,这样肯定不安全啦。

MongoDB用户权限分配的操作是针对某个库来说的。--这句话很重要。

下面演示如何给对应的库添加帐号密码:

1,进入命令模式

#mongod

2,进入某个库

#use test

3,添加用户

db.addUser("str","str");  

4,用户授权

#db.auth("str","str");

5,修改配置文件mongo.conf支持权限控制

#vim /etc/mongod.conf

把auth=true这行前面的注释去掉,保存即可

6,重启服务

#service mongod restart

程序再次链接test库的时候,如果不提供用户名和密码提示无链接权限。

程序连接如下,见红色部分:

Mongo mongoClient = null;
DB db = null;
DBCollection coll = null;

public Leantest(){
	try {
		mongoClient = new Mongo("localhost", 27017);
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
	db = mongoClient.getDB("test");
	db.authenticate("str", "str".toCharArray());
	//就是上面这行
	coll = db.getCollection("testCollection");
}

附上一些常用用户操作命令:

db.system.users.find();
查看所有用户

db.system.users.remove({user:"str"});

删除str用户

db.addUser("str","str1");

更改密码(为已经存在的用户更改密码)

猜你喜欢

转载自stranger2008.iteye.com/blog/1943139