在CakePHP 3上登录[Auth->;identify()]总是false


Login [ Auth->identify() ] always false on CakePHP 3

在使用CakePHP2一段时间后,我开始使用CakePHP 3,并且在创建身份验证登录时遇到了问题。

新的身份验证函数$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']);
    }
}

用户控制器:

[...]
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是推荐的,因为字符计数可以存储在一个字节中。

已解决:数据库上的类型小于所需类型。更改为varchar(255),现在工作正常:)

我遇到了同样的问题。登录名[Auth->identify()]对我不起作用。更改数据库中的密码长度将解决此问题。

嗨,分享我的片段到Login Auth,所有测试都可以,在CakePHP 3.1中,自定义(表+查看登录BootStrap 3+SQL基础+自定义BootStrap.php,适用于Inflector::rules(*******)中的西班牙语)

中的所有代码

https://bitbucket.org/snippets/eom/rLo49

我只添加了use Cake'Auth'DefaultPasswordHasher;及其下面的覆盖方法_setPassword就得到了一个解决方案。

这是变化:

Model/table.php

<?php
use Cake'Auth'DefaultPasswordHasher;
// Somewhere in the class
protected function _setPassword($password) {
    return (new DefaultPasswordHasher)->hash($password);
}