【问题标题】:CakePHP 3.6 $this->Auth->identify() returning FALSE on newly created dataCakePHP 3.6 $this->Auth->identify() 在新创建的数据上返回 FALSE
【发布时间】:2018-06-22 06:43:00
【问题描述】:

我目前在解决问题时遇到了一些困难。我是 cakePHP 3 的新手,被分配创建一个博客系统(用户、博客、角色)来进一步培训。我做的第一件事是插入身份验证部分。最初,登录工作正常(我使用 /users/add.ctp 通过 DefaultPasswordHasher 使用散列密码创建了 3 个帐户,并尝试使用每个帐户登录)。经过几天的网站前端设计工作后,我创建了 2 个新用户,并注意到 $user = $this->Auth->identify() 在我尝试登录其中一个新帐户时返回 false .我尝试使用我的一个旧帐户登录,并定义了 $user。为了测试它,我编辑了一个旧帐户的密码,并尝试使用新密码登录,现在 $user 现在返回 false。

这是我的代码:

//App Controller
$this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'fields' => ['username' => 'username','password' => 'password'],

            ]
        ],
        'authError' => 'Please login before continuing.',
        'loginAction' => ['controller' => 'Users', 'action' => 'login'],
        'loginRedirect' => ['controller' => 'Blogs', 'action' => 'index'],
        'logoutRedirect' =>  ['controller' => 'Users', 'action' => 'login'],
        'unauthorizedRedirect' => ['controller' => 'Users', 'action' => 'login']
    ]);

public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    $this->Auth->allow();



    $this->set(compact('session_user'));
}

这是我的用户控制器登录:

public function login()
{
    $this->viewBuilder()->setLayout('login');

    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        die(pr($user));  //<--To check if identify() catches login details
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        else {
            $this->Flash->error(__('Username/Password is invalid.'));
            return $this->redirect($this->Auth->config('loginAction'));
        }
    }
}

这是 login.ctp

<div class = "login-container">
<div class = "login-div">
    <div = "login-field">
        <h1>Login Page</h1>
        <?= $this->Form->create(); ?>
        <?= $this->Form->control('username') ?>
        <?= $this->Form->control('password', ['type' => 'password']) ?>
        <?= $this->Form->button(__('Login')) ?>
        <?= $this->Form->end() ?>
    </div>
</div>

这是我的用户实体:

class User extends Entity
{

/**
 * Fields that can be mass assigned using newEntity() or patchEntity().
 *
 * Note that when '*' is set to true, this allows all unspecified fields to
 * be mass assigned. For security purposes, it is advised to set '*' to false
 * (or remove it), and explicitly make individual fields accessible as needed.
 *
 * @var array
 */
protected $_accessible = [
    'username' => true,
    'role_id' => true,
    'email' => true,
    'password' => true,
    'created' => true,
    'modified' => true,
    'role' => true,
    'blogs' => true
];

/**
 * Fields that are excluded from JSON versions of the entity.
 *
 * @var array
 */
protected $_hidden = [
    'password'
];

public function _setPassword($value) {
    $hasher = new DefaultPasswordHasher();
    return $hasher->hash('$value');
}

}

这是我的用户表:

class UsersTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('users');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->addBehavior('Timestamp');

    $this->belongsTo('Roles', [
        'foreignKey' => 'role_id',
        'joinType' => 'INNER'
    ]);
    $this->hasMany('Blogs', [
        'foreignKey' => 'user_id'
    ]);
    $this->hasMany('Comments', [
        'foreignKey' => 'user_id'
    ]);
}

/**
 * Default validation rules.
 *
 * @param \Cake\Validation\Validator $validator Validator instance.
 * @return \Cake\Validation\Validator
 */
public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->scalar('username')
        ->maxLength('username', 255)
        ->requirePresence('username', 'create')
        ->notEmpty('username');


    $validator
        ->email('email')
        ->requirePresence('email', 'create')
        ->notEmpty('email');

    $validator
        ->scalar('password')
        ->maxLength('password', 255)
        ->requirePresence('password', 'create')
        ->notEmpty('password');

    return $validator;
}

/**
 * Returns a rules checker object that will be used for validating
 * application integrity.
 *
 * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
 * @return \Cake\ORM\RulesChecker
 */
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->isUnique(['username']));
    $rules->add($rules->isUnique(['email']));
    $rules->add($rules->existsIn(['role_id'], 'Roles'));

    return $rules;
}

}

我在 $this->Auth->identify(); 之后插入了 die(pr($user));在用户控制器的登录功能。通过在我的 localhost/phpmyadmin 和 users/view.ctp 中检查数据,我确信数据已被正确保存和散列,只是新创建/编辑的帐户似乎无法通过登录。

【问题讨论】:

    标签: authentication cakephp


    【解决方案1】:

    我知道我在哪里犯了错误。我在密码哈希的 _setPassword 函数中为 $value 加上了单引号。

    【讨论】:

    • 我已投票结束您的问题,因为它似乎是由于拼写错误。随意接受您自己的答案和/或接受我的投票以关闭答案。如果您愿意,您也可以删除问题。 From Review
    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2015-06-15
    • 2017-11-05
    相关资源
    最近更新 更多