Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't authenticate on mongodb with PHP

What i've done:

Enabled authentication in /etc/mongod.conf :

auth = true

Created the first user from the shell as stated in the doc :

db.createUser(
{
    user: "admin",
    pwd: "admin",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})

Using the admin user, i've created a root user to access mongodb:

db.createUser(
{
    user: "root",
    pwd: "root",
    roles: [ "root" ]
})

Until this point all works fine, as i can authenticate from the mongo shell with:

mongo --port 27017 -u root -p root  admin

and it works perfectly, as i can make all operations in the db.

The problem:

when i try to authenticate from PHP using the same root user:

$client = new MongoClient("mongodb://root:root@localhost:27017/admin");

It gives the error:

Failed to connect to: localhost:27017: Authentication failed on database 'admin' with username 'root': auth failed

Why can't PHP authenticate on mongodb if authenticating with the same credentials works fine from the mongo shell?

Other notes:

  • If I disable authentication PHP connects perfectly, and the mongo classes work fine
  • I've tried to create different users, but the response is the same
  • I am using Mongo 3.0.1, PHP 5.5.9 and Ubuntu 14.04.2 LTS 64bit
like image 434
Moppo Avatar asked Apr 22 '15 09:04

Moppo


2 Answers

Problem solved: apparenty it was caused by a problem/bug in the PHP mongo driver version 1.4

I've upgraded the driver to version 1.6 with:

pecl upgrade mongo

and now the authentication works.

like image 92
Moppo Avatar answered Sep 29 '22 17:09

Moppo


I've had the same problem, in my case I've installed mongo using apt-get

apt-get install php5-mongo

And seems that Ubuntu repositories has still the version 1.4 and hasn't updated the package yet. If you want to install mongo on Ubuntu you should use the pecl option

pecl install mongo

Never use apt-get for installing mongo for php.

like image 24
ventayol Avatar answered Sep 29 '22 18:09

ventayol