在CakePHP 3上登录[Auth-> identify()]始终为false
作者:互联网
我在使用CakePHP 2一段时间后开始使用CakePHP 3,我在创建身份验证登录时遇到了麻烦.
新的auth函数$this-> Auth-> identify()始终返回false.
在数据库上,密码是完美加密的,并且用户也可以查询.
我的代码:
AppController的:
[...]
class AppController extends Controller{
public function initialize(){
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Admin',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display'
]
]);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['display']);
}
}
UserController的:
[...]
class UsersController extends AppController{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['logout']);
}
[...]
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
[...]
用户(模型实体):
<?php
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class User extends Entity{
protected $_accessible = [*];
protected function _setPassword($password){
return (new DefaultPasswordHasher)->hash($password);
}
}
视图:
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Please enter your username and password') ?></legend>
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
解决方法:
CakePHP3默认使用不同的散列算法,而不是2(bcrypt与SHA1),因此您需要使密码长度更长.将您的密码字段更改为VARCHAR(255)是安全的.
当CakePHP 3尝试从此> Auth-> identify()与数据库中的哈希密码识别您的内存中哈希密码时,它将永远不会匹配,因为某些字符丢失.更改为255不仅仅是需要,但如果将来使用更安全的哈希,可以帮助将来证明.建议使用255,因为字符数可以存储在一个字节中.
标签:php,authentication,cakephp,cakephp-3-0,login 来源: https://codeday.me/bug/20190929/1830681.html