[英]CakePHP 2.5 - Authentication doesn't work
在学习完本教程后,我尝试创建简单的身份验证,但我无法登录-始终收到消息“用户名或密码无效,请重试”。 我不明白为什么-用户名和密码正确。 请帮助寻找错误。
我的模特
// 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();
}
}
我的看法(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>
数据库表“用户”:ID,用户名,密码(如md5)
对于AuthComponent,您已将SimplePasswordHasher
配置为使用“ md5”,但在beforeSave()回调中,您并未将其配置为使用md5(默认情况下,它使用sha1)。
SimplePasswordHasher
会在散列之前将安全性盐附加到您的密码上,因此,如果您在用户表中手动添加了记录而不添加了盐分,则该记录将不起作用。 无盐的md5哈希非常弱。 强烈建议不要使用它。 但是,如果您确实需要,则必须制作并使用自定义密码哈希器类,该类将生成不含盐的md5哈希。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.