Validating CakePHP users from other PHP service

auth-cakephp-php
Nowadays is very common to synchronize different applications, relate them somehow or even share the users accounts.

Working with a framework such as CakePHP make thing easier but at the same time it hides all those actions taking place behind the scenes.

CakePHP automatically hashes the user passwords to secure them and store the hash in the users table of the database. A hashed password with CakePHP 2.3 looks like this: f061c4f1a0b786c3b05dd0013a0230d767l19b77

How does it works?

Well, after examining the process taking place when login ($this->Auth->login()) we can easily notice that CakePHP makes use of its function `hash` (defined in lib\Cake\Utility\Security)to hash the user’s password and compare it with the value stored in the database.

public static function hash($string, $type = null, $salt = false) {
    if (empty($type)) {
        $type = self::$hashType;
    }
    $type = strtolower($type);

    if ($type === 'blowfish') {
        return self::_crypt($string, $salt);
    }
    if ($salt) {
        if (!is_string($salt)) {
            $salt = Configure::read('Security.salt');
        }
        $string = $salt . $string;
    }

    if (!$type || $type === 'sha1') {
        if (function_exists('sha1')) {
            return sha1($string);
        }
        $type = 'sha256';
    }

    if ($type === 'sha256' && function_exists('mhash')) {
        return bin2hex(mhash(MHASH_SHA256, $string));
    }

    if (function_exists('hash')) {
        return hash($type, $string);
    }
    return md5($string);
}

We can also notice it uses the PHP function `sha1` if there’s no `type` or it is defined as `sha1`, which means this will be the
default behavior as `type` is an optional parameter for the function defined as `null` by default.

As by default the `salt` parameter is defined to `false`, it will use the value stored in CakePHP configuration for it:

    Configure::read('Security.salt');

This value is extracted from `app\config\core.php`

The solution

Therefor, if we want to validate a user against CakePHP users table from outside CakePHP, we will only need to make use of the same `salt` value as our CakePHP application and then concatenate it with our user password to obtain the CakePHP hashed password:

sha1('cce93fda02c7f3ebf1g46c583589f1fd257e9d5d'. 'mypassword');