CakePHP2.4で、passwordHasherクラスを作成して利用する事で簡単にパスワードの暗号などをカスタマイズできます。
まずは予め用意されているモジュールを眺める事で、何を作ればよいか見てみたいと思います。
《注意》細かいところはだいぶ省いてます、、
CakePHPに予め用意されているpasswordHasherクラス
デフォルトではSimplePasswordHasherクラスを利用するので、中身を見てみます。
パスワードのチェック時には下記メソッドを使って、フォームで入力された文字列をハッシュ化して
DBの値とチェックします。
/**
* Config for this object.
*
* @var array
*/
protected $_config = array('hashType' => null);
/**
* Generates password hash.
*
* @param string $password Plain text password to hash.
* @return string Password hash
*/
public function hash($password) {
return Security::hash($password, $this->_config['hashType'], true);
}
Security::hashの中身を見てみると、上記よりハッシュのタイプは指定がないので、sha256
でハッシュ化される事がわかります。
独自のpasswordHasherクラス作成方法と設置場所について
CakePHP2.4が予め用意しているPasswordHasherクラスは
{CakePHP本体のパス}/lib/Cake/Controller/Component/Auth/以下に
- BlowfishPasswordHasher.php
- SimplePasswordHasher.php
がある事がわかります。なので、同じように
- {APPのパス}/Controller/Component/Auth/HogePasswordHasher.php
とファイルを作ってみます。
ファイルの中身は上記のBlowfishPasswordHasherクラスをコピーしてクラス名をHogePasswordHasherに変更。
class HogePasswordHasher extends AbstractPasswordHasher {
public function hash($password) {
return 自分で実装した暗号化ロジック;
}
public function check($password, $hashedPassword) {
return $hashedPassword === $this->hash($password);
}
}
これだけでOK。
利用するPasswordHasherの変更方法
AppControllerなど、認証を利用するクラスに下記内容を記述する
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Hoge'
)
)
)
);
以上の方法で簡単にpasswordHasherクラスの変更を行う事ができます。