1. Home
  2. 3rd Party Product
  3. MongoDB
  4. How to enable authentication on MongoDB

How to enable authentication on MongoDB

เนื่องจากโดย default แล้ว MongoDB จะไม่มีการ enable authentication มาให้ตั้งแต่แรก ส่งผลให้เมื่อ connect MongoDB แล้ว จะมีสิทธิ์ admin ในทันที ซึ่งกระทบต่อ security ของระบบ ดังนั้นจึงควร enable authentication ขึ้นมา เมื่อต้องการเปิด connection จากภายนอกเข้าสู่ mongoDB

ขั้นตอนการ enable authentication สามารถทำได้ดังนี้

  1. connect เข้าไปยัง MongoDB
    mongo
  2. เปลี่ยนไปใช้ database admin
    use admin
  3. สร้าง user พร้อมกำหนด password
    db.createUser(
    {
    user: “myadmin”,
    pwd: “AdminP@ssw0rd”,
    roles: [ { role: “userAdminAnyDatabase”, db: “admin” } ]
    }
    )
  4. แก้ไขไฟล์ /etc/mongod.conf เพิ่มบรรทัด
    security:
    authorization: enabled
  5. restart service
    systemctl restart mongod
  6. ทดสอบใช้งาน
    mongo
    show dbsจะต้องแสดง error message ว่าError: listDatabases failed:{
    “ok” : 0,
    “errmsg” : “not authorized on admin to execute command { listDatabases: 1.0, $db: \”admin\” }”,
    “code” : 13,
    “codeName” : “Unauthorized”
  7. เมื่อใช้งาน ให้ login ด้วย command ดังนี้
    db.auth(“myadmin”, “AdminP@ssw0rd”)จะได้ผลลัพธ์เป็น 1 เมื่อ login สำเร็จ

Reference

https://docs.mongodb.com/v3.2/tutorial/enable-authentication/

https://www.blognone.com/node/88956

Was this article helpful?