0

I'm playing around with a few projects to learn MongoDB, and one of the things I'm looking to add is an authentication mechanism to a website.

When using a traditional RDBMS, you can find a plethora of libraries for automating a lot of the intricacies of authentication, is there something out there for MongoDB?

I'm either looking for:

a) something that is simple and works out of the box with MongoDB, or b) something that is simple enough that I can just throw passwords at it and get a sane hash out of it.

Is there anything like that out there?

NOTE: I'm not talking about the built-in MongoDB authentication. I mean I want to build an authentication layer in a website that uses MongoDB as a data store. If all else fails, I can do the heavy lifting so long as I have something that's good about abstracting the salting/hashing so I don't have to worry about getting it right.

Fred
  • 3,786
  • 7
  • 41
  • 52

2 Answers2

1

PHP has the hash functions you need already. I prefer to use hash_pbkdf2(), but it is only available in latter versions of PHP. So I often use the less-standardized crypt() function.

They both work essentially the same way: You take the password, an algorithm, and some salt, and you hash the password many times over (thousands). The output hash includes the extra parameters that went into it (algorithm, salt, and rounds) so you can re-create the hash when someone tries to log in.

The advantages of both techniques are:

  • You have your choice of hashing algorithm
  • The addition of random salt makes dictionary attacks much harder
  • The additional rounds of hashing makes brute-force attacks much harder.

I've written a short example, with a little unit test.

/*  Hashes a password using 2000 rounds of SHA-256 and a random salt. 
    Returns a string.
*/
function hashpw($password) {
    $algo = '$5$rounds=2000$'; // specify SHA-256
    $salt = $algo . mt_rand();
    return crypt(strval($password), $salt);
}

/*  Given a password and a hash produced by hashpw(), tells you if the hash
    belongs to the password or not.  
    Returns a boolean. 
*/
function confirmpw($password, $hash) {
    return (crypt(strval($password), strval($hash)) === $hash);
}

$passwords = array(
    'hello world',
    'secret',
    'super-secret',
    'my pets name',
);

foreach($passwords as $onePass) {
    $hash = hashpw($onePass);
    $verified = confirmpw($onePass, $hash) ? 'verified' : 'failed' ;

    echo "$onePass ==> $hash ==> $verified \n";
}
slashingweapon
  • 11,007
  • 4
  • 31
  • 50
0

There's this for Codeigniter: https://github.com/pawankorotane/mongodb-tank-auth

In case you're not using CodeIgniter, you can always check the code and modify for the framework that you use.

priyolahiri
  • 668
  • 1
  • 5
  • 10
  • This is not very easy to convert to a normal PHP application, also judging by the lack of use of it I would say it isn't tried and tested either – Sammaye Jun 06 '13 at 14:13