Can't authenticate on mongodb with PHP

12,144

Solution 1

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.

Solution 2

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.

Share:
12,144
Moppo
Author by

Moppo

I'm Francesco Moroni, a Freelance Software Engineer working in PHP, Javascript and MySQL I'm currently focused in application development with Laravel, but also experienced in Java, C++, MongoDB and Game programming http://www.francescomoroni.com

Updated on July 23, 2022

Comments

  • Moppo
    Moppo almost 2 years

    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