下面的教程我试图创建简单的身份验证,但我无法登录-总是得到一个消息"无效的用户名或密码,再试一次"。我不明白为什么-用户名和密码是正确的。请帮忙找出错误
我的模型// app/Model/User.php
App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
我的控制器
// app/Controller/UsersController.php
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('logout');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'good',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'login',
'action' => 'index',
'home'
),
'authenticate' => array(
'Form' => array(
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'md5'
)
)
)
)
);
public function beforeFilter() {
$this->Auth->deny();
}
}
My view (login.ctp)
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend>
<?php echo __('Please enter your username and password'); ?>
</legend>
<?php echo $this->Form->input('username', array('label' => 'Username'));
echo $this->Form->input('password', array('label' => 'Password'));
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
数据库表"users": id,username, password (md5)
-
对于AuthComponent,你已经配置了
SimplePasswordHasher
使用"md5",但在你的beforeSave()回调中,你没有配置它使用md5(它默认使用sha1)。 -
SimplePasswordHasher
将在散列之前将安全盐附加到您的密码中,因此,如果您在用户表中手动添加记录而不加盐,则无法工作。无盐md5哈希非常弱。强烈建议不要使用它。但是如果你真的想这样做,你将不得不创建和使用一个自定义密码哈希器类,它可以不加盐地生成md5哈希。