このガイドは、MongoDBで認証を有効にする方法を示しています。認証はデフォルトでは無効になっています。これを設定するには、最初に “admin”データベースにユーザを追加する必要があります。

> show dbs
admin  #add single user to this database
testdb


P.Sこの例では、MongoDBのバージョン2.2.3

認証の例

adminデータベースに “admin”ユーザを追加する例と、 “testdb”データベースに通常のユーザを追加する完全な例と、認証を実行する方法を参照してください。

ターミナル1 – MongoDBをセキュアモードで起動するには、認証が必要です。

$mongo --auth

第2ターミナル – MongoDBクライアント、コメント “#”を参照してください。

$ mongo
MongoDB shell version: 2.2.3
connecting to: test
> use admin                  #1. connect to the "admin" database.
switched to db admin
> db.addUser("admin","password") #2. add a user "admin" to the admin database.
{
    "user" : "admin",
    "readOnly" : false,
    "pwd" : "90f500568434c37b61c8c1ce05fdf3ae",
    "__id" : ObjectId("513af8cac115e7a6b4bcceb9")
}
addUser succeeded, but cannot wait for replication since we no longer have auth

> use testdb             #3. connect to the "testdb" database.
switched to db testdb
> show collections           #4. now, read and write need authentication
Sat Mar  9 16:54:57 uncaught exception: error: {
    "$err" : "unauthorized db:testdb ns:testdb.system.namespaces lock type:0 client:127.0.0.1",
    "code" : 10057
}
> use admin              #5. connect back to the "admin" database.
switched to db admin
> db.auth("admin","password")        #6. performs authentication, 1 means succeed, 0 means failed
1
> use testdb             #7. connect to the "testdb" database.
switched to db testdb
> show collections           #8. no problem, it shows all collections
system.indexes
user
> db.addUser("testdb","password")       #9. add another user "testdb" to the "testdb" database.
{
    "user" : "testdb",
    "readOnly" : false,
    "pwd" : "b9ff75cbf18bd98d8554efec12c72090",
    "__id" : ObjectId("513af934c115e7a6b4bcceba")
}
> show collections
system.indexes
system.users                #10. All users' data are stored in this system.users collection.
user
> db.system.users.find()
{ "__id" : ObjectId("513af934c115e7a6b4bcceba"), "user" : "testdb", "readOnly" : false, "pwd" : "b9ff75cbf18bd98d8554efec12c72090" }
>

完了しました。

参考文献

セキュリティの実践と管理]。リンク://mongodb/java-authentication-access-to-mongodb/[Java MongoDB

認証の例]

リンク://タグ/認証/[認証]リンク://タグ/mongodb/[mongodb]