php - $this->Auth->identify(); 在 cakephp 3.6.6 中总是返回假值
问题描述
我需要使用 CakePHP 3.3.6 在我的应用程序中实现登录系统我使用了身份验证组件,但它不能正常工作。
方法 $this->Auth->identify(); 总是返回 false 为什么?
这是我的代码:
实体模型中的 User.php
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
class User extends Entity
{
protected $_accessible = [
'email' => true,
'password' => true,
'date_created' => true
];
protected $_hidden = [
'password'
];
protected function _setPassword($password){
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
}
登录控制器:
<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Event\Event;
class LoginController extends AppController
{
public function index(){
if($this->request->is('post')){
$user = $this->Auth->identify();
if($user){
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
else{
$this->Flash->error('Incorrect Login');
}
}
}
}
索引.ctp:
<div class="row">
<div class="columns large-3"> </div>
<div class="panel columns large-6">
<div class="text-center">
<h3>Login</h3>
</div>
<?= $this->Form->create(); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('password',['type'=>'password']); ?>
<?= $this->Html->link('Do not have an account?',['controller'=>'login','action'=>'register'],['class'=>'pull-right']) ?>
<?= $this->Form->submit('Login',['class'=>'button']); ?>
<?= $this->Form->end(); ?>
<?= $this->Flash->render() ?>
</div>
<div class="columns large-3"> </div>
</div>
应用控制器:
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash');
$this->loadComponent('Security');
$this->loadComponent('Csrf');
$this->loadComponent('SessionsActivity');
$this->loadComponent('Auth',[
'authenticate' =>[
'Form' => [
'fields' => [
'email' => 'email',
'password' =>'password'
]
]
],
'loginAction' => [
'controller' => 'Login',
'action' => 'index'
],
'storage' => 'Session',
]);
$this->loadComponent('Security');
}
}
在用户表中有用于验证凭据的电子邮件或密码文件。
解决方案
推荐阅读
- botframework - Bot Framework V4 上的对话继续问题
- reactjs - React 中的 Apollo 客户端和 graphQl 的 cookie 身份验证如何工作
- json - 从 API 检索时出现 JSON 响应错误 NSSingleObjectArray
- dart - 如何在 Dart 的循环中更改对象值
- python - 在 docker 中使用 Python web-server 使用 ML 模型回答 post 请求
- rust - 更新/重新初始化在lazy_static中定义的变量
- javascript - 如何以参数方式将 json 正文中的字段发送到节点 js api?
- websocket - AWS APIGateway WebSockets API 返回 429
- sqlite - 使用 Centos7 的 SQlite 二进制文件升级 Python SQlite3 模块(本地机器)
- google-drive-api - 使用 Soup (Vala) 在 Google Drive API 中获取错误“可能正在发送自动查询”