1. 添加用戶
MongoDB shell version: 1.8.2
connecting to: 127.0.0.1:30000/test
>
>
>
> use admin
switched to db admin
> db.addUser('admin','admin')
{
"user" :
"admin",
"readOnly" :
false,
"pwd" :
"7c67ef13bbd4cae106d959320af3f704"
}
>
2. 帶上--auth參數後重啓
$MONGODB_HOME/bin/mongod --fork --logpath=$MONGODB_HOME/logs/mongodb.log --dbpath=$DATA_PATH --port=$MONGODB_PORT
--auth
3. 測試
MongoDB shell version: 1.8.2
connecting to: 127.0.0.1:30000/test
>
> use admin
switched to db admin
> show collections
Sat Aug 6 11:16:45 uncaught exception: error: {
"$err" :
"unauthorized db:admin lock type:-1 client:127.0.0.1",
"code" : 10057
}
switched to db admin
>
db.auth('admin','admin')
1
> show collections
system.indexes
system.users
>
沒有執行
db.auth('admin','admin')以前會報錯,說是未受權
4. Java客戶端調用也須要使用用戶名和密碼,只需簡單地加上一句
db.authenticate(
"admin",
"admin".toCharArray());
5. 在admin下添加的用戶是超級管理員,能夠訪問任何數據庫,用超級管理員能夠爲單個數據庫添加用戶,這個用戶只能訪問他所在的數據庫
> use test
switched to db test
> db.addUser(
"test",
"test")
{
"user" :
"test",
"readOnly" :
false,
"pwd" :
"a6de521abefc2fed4f5876855a3484f5" }
6. 在未受權的狀況下,依然能夠執行db.shutdownServer()停掉節點因此運行mongodb的服務器端口必定要嚴格受權訪問