How do I replace the cakephp password hashing algorithm?
Asked Answered
R

3

6

I have an existing database I'm trying to put a cake app on top of. The old app used crypt() in Perl to hash the passwords. I need to do the same in the PHP app.

Where is the correct place to make that change in a standard cakephp app? And what would such a change look like?

Robichaux answered 21/2, 2009 at 16:20 Comment(0)
R
8

I got it working...

here is my AppController:

class AppController extends Controller {
    var $components = array('Auth');

    function beforeFilter() {
        // this is part of cake that serves up static pages, it should be authorized by default
        $this->Auth->allow('display');
        // tell cake to look on the user model itself for the password hashing function
        $this->Auth->authenticate = ClassRegistry::init('User');
        // tell cake where our credentials are on the User entity
        $this->Auth->fields = array(
           'username' => 'user',
           'password' => 'pass',
        );
        // this is where we want to go after a login... we'll want to make this dynamic at some point
        $this->Auth->loginRedirect = array('controller'=>'users', 'action'=>'index');
    }
}

Then here is the user:

<?php
class User extends AppModel {
    var $name = 'User';

    // this is used by the auth component to turn the password into its hash before comparing with the DB
    function hashPasswords($data) {
         $data['User']['pass'] = crypt($data['User']['pass'], substr($data['User']['user'], 0, 2));
         return $data;
    }
}
?>

Everything else is normal, i think.

Here is a good resource: http://teknoid.wordpress.com/2008/10/08/demystifying-auth-features-in-cakephp-12/

Robichaux answered 21/2, 2009 at 23:35 Comment(0)
W
2

Actually the above described method by danb didn't work for me in CakePHP 2.x Instead I ended up creating a custom auth component to bypass the standard hashing algorithm:

/app/Controller/Component/Auth/CustomFormAuthenticate.php

<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');

class CustomFormAuthenticate extends FormAuthenticate {

    protected function _password($password) {
        return self::hash($password);
    }

    public static function hash($password) {
        // Manipulate $password, hash, custom hash, whatever
        return $password;
    }
}

...and then use that in my controller...

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'CustomForm' => array(
                'userModel' => 'Admin'
            )
        )
    )
);

This last block can also be put inside the beforeFilter method of the AppController. In my case I just choose to put it specifically in one controller where I was going to use custom authentication with a different user model.

Wriggly answered 2/5, 2012 at 22:17 Comment(4)
The filename needs to be CustomFormAuthenticate.php - not CustomFormAuthentication.phpHubie
@Wriggly I know this is a 5 month old thread but would you know how to structure CustomFormAuthenticate class if I need to use cryp with email as salt. Obviously, email is not accessible at this point? Please help!Venose
@Venose I think you'd have to pass the email into the custom hash function from the beforeSave callback of your model: gist.github.com/4689966 - And then of course in your custom has function you can do something like : return crypt($password,$email); Hope that helps!Wriggly
Thanks @Wriggly I was not able to modify the custom hash method directly, but I overrode authenticate() method in CustomFormAuthenticate and used $request to get the username, which I saved to a property. not sure if this is the best way to do, but it worked!! Thanks again :)Venose
C
1

Just to follow this up in CakePHP 2.4.1, I was building a front-end for a legacy database that had existing user passwords stored as md5(accountnumber:statictext:password), and to allow users to login we needed to use that hashing system as well.

The solution was:

Create a file app/Controller/Component/Auth/CustomAuthenticate.php with:

<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');

class CustomAuthenticate extends FormAuthenticate {

    protected function _findUser($username, $password = null) {
        $userModel = $this->settings['userModel'];
        list(, $model) = pluginSplit($userModel);
        $fields = $this->settings['fields'];

        if (is_array($username)) {
            $conditions = $username;
        } else {
            $conditions = array(
                $model . '.' . $fields['username'] => $username
            );

        }

        if (!empty($this->settings['scope'])) {
            $conditions = array_merge($conditions, $this->settings['scope']);

        }

        $result = ClassRegistry::init($userModel)->find('first', array(
            'conditions' => $conditions,
            'recursive' => $this->settings['recursive'],
            'contain' => $this->settings['contain'],
        ));
        if (empty($result[$model])) {
            return false;
        }

        $user = $result[$model];
        if ($password) {
            if (!(md5($username.":statictext:".$password) === $user[$fields['password']])) {
                return false;
            }
            unset($user[$fields['password']]);
        }

        unset($result[$model]);
        return array_merge($user, $result);
    }

}

The "extends FormAuthenticate" means that this file takes over the _findUser function but defers to FormAuthenticate for all other functions as normal. This is then activated by editing AppController.php and adding to the AppController class something like this:

public $components = array(
    'Session',
    'Auth' => array(
        'loginAction' => array('controller' => 'accounts', 'action' => 'login'),
        'loginRedirect' => array('controller' => 'accounts', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
        'authenticate' => array (
            'Custom' => array(
                'userModel' => 'Account',
                'fields' => array('username' => 'number'),
            )
        ),
    )
);

In particular note the use of the associative array key 'Custom'.

Finally it's necessary to hash the password when creating a new user, so to the model file (in my case Account.php) I added:

public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = md5($this->data[$this->alias]['number'].":statictext:".$this->data[$this->alias]['password']);
    }
    return true;
}
Cringe answered 21/10, 2013 at 7:31 Comment(3)
Thank you very much @Cringe ! Thanks to your response I was able to make my password process works !Petrous
Moreover this solution let us choose the model that will handle the Auth process.Petrous
Glad to have helped :-)Cringe

© 2022 - 2024 — McMap. All rights reserved.