データベースに認証を設定して開く

概要

データベースに認証を設定することで認証をしてデータを制御することが可能

しかし、localhost環境のPCからは認証なしでもアクセス可能


サーバの処理

パラメータに「--auth」を指定して起動することで認証機能を設定できる

D:\>mongod --port 10000 --dbpath "D:\Tools\Works\mongodb\data" --auth
Wed Apr 10 21:59:16.023 [initandlisten] MongoDB starting : pid=6308 port=10000 dbpath=D:\Tools\Works\mongodb\data 64-bit host=wkpc-mshige1979
Wed Apr 10 21:59:16.028 [initandlisten] db version v2.4.1
Wed Apr 10 21:59:16.029 [initandlisten] git version: 1560959e9ce11a693be8b4d0d160d633eee75110
Wed Apr 10 21:59:16.030 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
Wed Apr 10 21:59:16.032 [initandlisten] allocator: system
Wed Apr 10 21:59:16.033 [initandlisten] options: { auth: true, dbpath: "D:\Tools\Works\mongodb\data", port: 10000 }
Wed Apr 10 21:59:16.068 [initandlisten] journal dir=D:\Tools\Works\mongodb\data\journal
Wed Apr 10 21:59:16.070 [initandlisten] recover : no journal files present, no recovery needed
Wed Apr 10 21:59:16.583 [initandlisten] waiting for connections on port 10000
Wed Apr 10 21:59:16.583 [websvr] admin web console waiting for connections on port 11000
 
 
 

クライアントの処理

クライアントを「localhost」で起動

D:\>mongo --host localhost --port 10000
MongoDB shell version: 2.4.1
connecting to: localhost:10000/test
>
 
 

データベースを指定

> use auth_test01
switched to db auth_test01
>
 
 

ユーザーを追加

> db.addUser("admin", "password")
{
        "user" : "admin",
        "readOnly" : false,
        "pwd" : "90f500568434c37b61c8c1ce05fdf3ae",
        "_id" : ObjectId("516562e26142533c14a75c11")
}
>
 
 

一度、終了して、ローカルでアクセス

D:\>
D:\>mongo --host localhost --port 10000
MongoDB shell version: 2.4.1
connecting to: localhost:10000/test
>
> use auth_test01
switched to db auth_test01
>
> db.sample.insert({"aaa": "111"})
>
> db.sample.find()
{ "_id" : ObjectId("5165633ab10a5310ce74167a"), "aaa" : "111" }
>
>
 
 
localhostはシステムユーザーなのかアクセスできる

IPを変更してアクセス

D:\>mongo --host 192.168.11.2 --port 10000
MongoDB shell version: 2.4.1
connecting to: 192.168.11.2:10000/test
>
> use auth_test01
switched to db auth_test01
>
> db.sample.find()
error: { "$err" : "not authorized for query on auth_test01.sample", "code" : 16550 }
>
 
 
認証していないのでエラーとなった

認証を実行

> db.auth("admin","password")
1
>
> db.sample.find()
{ "_id" : ObjectId("5165633ab10a5310ce74167a"), "aaa" : "111" }
>
 
 
認証が成功したので表示できた


ログイン時にユーザーを指定して認証

D:\>mongo auth_test01 --host 192.168.11.2 --port 10000 -u admin -p password
MongoDB shell version: 2.4.1
connecting to: 192.168.11.2:10000/auth_test01
>
> db.sample.find()
{ "_id" : ObjectId("5165633ab10a5310ce74167a"), "aaa" : "111" }
>
 
 
起動時にデータベースとユーザー、パスワードを指定している場合は認証可能



最終更新:2013年04月10日 22:19